wpf 将数据集/数据表绑定到 xaml 数据网格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17179871/
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 a dataset/DataTable to a xaml datagrid
提问by voonna
I want to display a datagrid in my UI. I am binding it to a dataset in my viewmodel. Here is the code:
我想在我的 UI 中显示一个数据网格。我将它绑定到我的视图模型中的数据集。这是代码:
View:
看法:
<StackPanel Orientation="Horizontal" Height="Auto" Name="stackPanel4" Width="Auto" Grid.Row="4">
<DataGrid Name="QueryGrid" AutoGenerateColumns="True" Height="1000" Width="1000" ItemsSource="{Binding QueryTable}" Visibility="{Binding Path=QueryGridVisiblity, Converter={StaticResource BoolToVis}}" />
</StackPanel>
ViewModel:
视图模型:
private void OnRunQuery()
{
int count = 0;
DataSet queryDataset = null;
if (flag1 == true)
count++;
else if (flag2 == true)
count++;
else if (flag3 == true)
count++;
else if (flag4 == true)
count++;
else if (flag5 == true)
count++;
else if (flag6 == true)
count++;
if (paramCount > 0 && sqlQuery != null && paramCount == count)
{
queryDataset = _service.GetQueryDataSource(sqlQuery);
m_QueryTable = queryDataset;
OnPropertyChanged("QueryTable");
m_Visibility = true;
OnPropertyChanged("QueryGridVisiblity");
}
}
private DataSet m_QueryTable;
public DataSet QueryTable
{
get
{
return m_QueryTable;
}
set
{
m_QueryTable = value;
OnPropertyChanged("QueryTable");
}
}
Up on executing the application, the datagrid is not populated. But i get the data in my dataset.
在执行应用程序时,不会填充数据网格。但是我在我的数据集中得到了数据。
Any suggestions where i am missing the logic? I am new to WPF.
在我缺少逻辑的地方有什么建议吗?我是 WPF 的新手。
回答by devdigital
You'll need to bind to a property on your view model that returns a DataView. Have a look at http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examplesfor more information.
您需要绑定到视图模型上返回DataView. 查看http://www.codeproject.com/Articles/30905/WPF-DataGrid-Practical-Examples了解更多信息。
E.g:
例如:
public DataView Items
{
get
{
return m_QueryTable.Tables[0].DefaultView;
}
}
Alternatively (and preferably), you could use entities and a repository pattern to abstract the data access logic away from the view models.
或者(最好),您可以使用实体和存储库模式将数据访问逻辑从视图模型中抽象出来。
回答by HichemSeeSharp
A DataSetis a set of DataTables and a DataGridshows only one DataTable. so expose a DataTableProperty instead of DataSet.
ADataSet是一组DataTables 而 aDataGrid仅显示一个DataTable。所以公开一个DataTableProperty 而不是DataSet.
回答by David Rauca
Use the table name without the quotes
使用不带引号的表名
E.g:
例如:
ItemsSource="{Binding ProductsDataSet.Tables[Products]}"
ItemsSource="{Binding ProductsDataSet.Tables[Products]}"

