将DataTable绑定到DataGrid. WPF MVVM [英] Binding DataTable to DataGrid. WPF MVVM
问题描述
我试图在Datagrid上绑定一个Datatable以便能够动态填充它. Datagrid似乎找到了Datatable,因为当我填充它并且在RaisePropertyChanged之后,我有很多空白行.也没有列.
I am trying to bind a Datatable on a Datagrid to be able to fill it dynamically. The Datagrid seems to find the Datatable because when I fill it and after the RaisePropertyChanged I have a lot of blank rows. There are no columns too.
我的视图:
<UserControl x:Class="NWViewer.View.DataGridView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:NWViewer.View"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding DataGrid, Source={StaticResource Locator}}">
<Grid>
<DataGrid ItemsSource="{Binding oTable.DefaultView}" AutoGenerateColumns="True" ColumnWidth="25">
</DataGrid>
</Grid>
</UserControl>
我的ViewModel:
public DataTable oTable { get;set;}
private void getNewData(List<ElementBaseViewModel> rootElement)
{
oTable.Clear();
foreach (var element in rootElement)
{
buildFromChildren(element);
}
RaisePropertyChanged("oTable");
}
private void buildFromChildren(ElementBaseViewModel element)
{
if(element.Children != null)
{
if (isAttributeChildren(element))
{
DataRow oRow = oTable.NewRow();
foreach (var attribute in element.AttributeChildren)
{
Model.Attribute attr = (Model.Attribute)attribute.Element;
if (!oTable.Columns.Contains(attr.name))
oTable.Columns.Add(attr.name);
oRow[attr.name] = attr.Value;
}
oTable.Rows.Add(oRow);
}
foreach (var elem in element.ElementChildren)
{
buildFromChildren(elem);
}
}
}
这是图形渲染:
但是当我调试它时,DataTable似乎正确填充了:
But the DataTable seems correctly filled when i debug it :
推荐答案
问题很可能与DataTable
初始化有关,DataGrid
将在设置新的ItemsSource
时自动生成列,但它将初始化后将列添加到基础表中时,不会重新生成列.
The problem is most probably related to the DataTable
initialization, DataGrid
will auto-generate columns when a new ItemsSource
is set, but it will not re-generate columns when columns are added to the underlying table after initialization.
解决方案1:
在将DataTable
绑定到DataGrid
之前,在初始化DataTable
时创建所有列.
Create all columns on initialization of the DataTable
, before binding it to the DataGrid
.
解决方案2:
强制刷新ItemsSource
.它应该像这样工作,但是如果可能的话,我强烈建议解决方案1:
Force refresh the ItemsSource
. It should work like this, but I highly recommend Solution 1 if possible:
var tempTable = oTable;
oTable = null;
RaisePropertyChanged("oTable");
oTable = tempTable;
RaisePropertyChanged("oTable");
这篇关于将DataTable绑定到DataGrid. WPF MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!