将数据表绑定到 WPF 中的数据网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30445620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding Datatable to a datagrid in WPF
提问by Mitu
I have a view model in my C# 4.0 app which has a System.Data.DataTablethat's created in it using a service call. I want to bind this to a datagridin my XAML file.
我的 C# 4.0 应用程序中有一个视图模型,它有一个System.Data.DataTable使用服务调用在其中创建的视图模型。我想将此绑定到datagrid我的 XAML 文件中的 a。
I tried following line DataGrid_Loaded event but its getting fired up before my datatable gets created inside the view model.
我尝试了以下行 DataGrid_Loaded 事件,但它在我的数据表在视图模型中创建之前就被触发了。
xaml:
xml:
<dg:DataGrid Name="myDataGrid" Loaded="DataGrid_Loaded"/>
xaml.cs:
xaml.cs:
myDataGrid.ItemsSource = myViewModel.myDataTable.DefaultView;
回答by PiotrWolkowski
Check the following suggestion: In your code behind you have to set grid's DataContextto your DataTable:
检查以下建议:在您后面的代码中,您必须将网格设置DataContext为您的DataTable:
myDataGrid.DataContext = myViewModel.myDataTable.DefaultView;
In your XAML you need to indicate that the ItemsSourcehas to rely on binding:
在您的 XAML 中,您需要指出ItemsSource必须依赖绑定:
<dg:DataGrid Name="myDataGrid" ItemsSource="{Binding}"/>
Follow this linkfor more details. Also, you can find a comprehensive example with explanations on CodeProject.
点击此链接了解更多详情。此外,您可以在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.
这样,您在主窗口 XAML 中的绑定将知道在哪里搜索数据输入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:
在您的 XAML 中,您不需要使用这种方法为您的网格命名。但是绑定必须指定数据源的名称:
<DataGrid ItemsSource="{Binding myDataTable}" AutoGenerateColumns="True"/>

