将数据可绑定到WPF中的数据网格 [英] Binding Datatable to a datagrid in WPF

查看:160
本文介绍了将数据可绑定到WPF中的数据网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#4.0应用程序中有一个视图模型,它具有使用服务调用在其中创建的 System.Data.DataTable 。我想将它绑定到我的XAML文件中的 datagrid



我尝试了以下行DataGrid_Loaded事件,但它得到在我的数据表在视图模型中创建之前就已经开始了。



xaml:

 < dg:DataGrid Name =myDataGridLoaded =DataGrid_Loaded/> 

xaml.cs:

  myDataGrid.ItemsSource = myViewModel.myDataTable.DefaultView; 


解决方案

检查以下建议:在您的代码背后有将网格的 DataContext 设置为 DataTable

  myDataGrid.DataContext = myViewModel.myDataTable.DefaultView; 

在您的XAML中,您需要指出 ItemsSource 必须依赖绑定:

 < dg:DataGrid Name =myDataGridItemsSource ={Binding}/ > 

按照这个链接有更多的细节。另外,您可以在 CodeProject 上找到一个全面的说明。



编辑:



不同的方法是将您的表保留为属性。在窗口中,将窗口的数据上下文设置为视图模型,然后在视图模型中设置绑定到属性:



视图模型:

  public DataTable myDataTable {get;组; 

在您的窗口(显示数据网格的窗口:

  public MainWindow()
{
InitializeComponent();
this.DataContext = myViewModel;
}

这样你的主窗口XAML中的绑定将知道在哪里搜索数据 - 在 myViewModel



在您的XAML中,您不需要使用此方法的网格名称,但绑定必须指定名称的数据源:

 < DataGrid ItemsSource ={Binding myDataTable}AutoGenerateColumns =True/> 


I have a view model in my C# 4.0 app which has a System.Data.DataTable that's created in it using a service call. I want to bind this to a datagrid in my XAML file.

I tried following line DataGrid_Loaded event but its getting fired up before my datatable gets created inside the view model.

xaml:

<dg:DataGrid Name="myDataGrid" Loaded="DataGrid_Loaded"/>

xaml.cs:

myDataGrid.ItemsSource = myViewModel.myDataTable.DefaultView;

解决方案

Check the following suggestion: In your code behind you have to set grid's DataContext to your DataTable:

myDataGrid.DataContext = myViewModel.myDataTable.DefaultView;

In your XAML you need to indicate that the ItemsSource has to rely on binding:

<dg:DataGrid Name="myDataGrid" ItemsSource="{Binding}"/>

Follow this link for more details. Also, you can find a comprehensive example with explanations on CodeProject.

EDIT:

Different approach would be to keep your table as a property. In your window to set the window's data context to the view model and then set the binding to the property in the view model:

The view model:

public DataTable myDataTable { get; set; }

In your window (the one that displays the data grid:

public MainWindow()
{
    InitializeComponent();
    this.DataContext = myViewModel;
}

This way your binding in main window XAML will know where to search for the data - in myViewModel.

In your XAML you don't need a name for your grid using this approach. But the binding has to specify the name of the data source:

<DataGrid ItemsSource="{Binding myDataTable}" AutoGenerateColumns="True"/>

这篇关于将数据可绑定到WPF中的数据网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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