将WPF DataGrid控件数据绑定到System.Data.DataTable对象? [英] Data-Binding a WPF DataGrid Control to a System.Data.DataTable Object?

查看:70
本文介绍了将WPF DataGrid控件数据绑定到System.Data.DataTable对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做才能使WPF DataGrid控件绑定到DataTable对象?

What do I need to do to get my WPF DataGrid control to bind to a DataTable object?

我已经为此苦了几天.即使绑定和查询都正常工作,并且表中有可观察到的数据-数据网格中也没有任何显示.

I've been suffering over this for several days now. Even when the binding and the query both work correctly, and there is observable data in the table - nothing shows up in the data grid.

我的XAML代码类似于:

My XAML code resembles this:

<Window x:Class="DataGridTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:TK="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
    Title="Window1" Height="300" Width="300">
        <Grid>
            <TK:DataGrid ItemsSource="{Binding Path=DTUsers}" />
        </Grid>
</Window>

我的C#背后的代码类似于:
(DAO是我的数据访问对象)

My C# code-behind resembles this:
(DAO is my Data Access Object)

public partial class Window1 : Window
{
    public dao DAO = new dao (ConnectionString) ;
    public System.Data.DataTable DTUsers { get; set; }

    public Window1()
    {
        InitializeComponent();

        if (DAO != null)
            DTUsers = DAO.Query( @"SELECT * FROM users" );
            // Returns a DataTable object containing user records.
            // I have confirmed that this returns my data correctly.
    }
}

我已经检查了输出,没有任何绑定错误.
为什么会编译并运行它,但不显示任何数据???

I've checked the output, and there are no binding errors.
Why will this compile and run, but won't display any data???

(如果您不知道DataGrid控件在哪里,则可以使用WPF工具包

(If you don't know where the DataGrid control is, the WPF Toolkit is available here. Install it, add a reference to WPFToolkit.dll [which will show up in the "Add Reference" dialog under ".NET"], and provide the XML namespace declaration [in my XAML above] to use the WPF DataGrid control.)

推荐答案

InitializeComponent()将实例化标记,包括绑定.此时, DTUsers 仍然为 null ,因此什么也不显示.然后,您更改 DTUsers ,但是绑定(因此网格)无法知道您已完成操作-因此它不会执行任何操作.

InitializeComponent() will instantiate your markup, including the binding. At that point DTUsers is still null, so nothing is displayed. Then, you change DTUsers, but there's no way for the binding (and therefore the grid) to know that you did it - and so it does not do anything.

您应该将 DTUsers 设置为依赖项属性,或者在您的类上实现 INotifyPropertyChanged ,并在更改的值后引发 PropertyChanged 事件财产.

You should either make DTUsers a dependency property, or implement INotifyPropertyChanged on your class, and raise PropertyChanged event after you change the value of the property.

这篇关于将WPF DataGrid控件数据绑定到System.Data.DataTable对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆