将DataTable绑定到DataGrid。 WPF MVVM
问题描述:
我想绑定Datagrid上的Datatable,以便能够动态地填充它。 Datagrid似乎找到了Datatable,因为当我填充它并在RaisePropertyChanged后面有很多空行时。没有列。将DataTable绑定到DataGrid。 WPF MVVM
笔者认为:
<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>
我的视图模型:
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似乎正确填写:
答
该问题最有可能涉及到DataTable
初始化,DataGrid
将自动生成列时,新的ItemsSource
设置,但不会重新 - 在初始化后将列添加到基础表时生成列。
解决方案1:
它绑定到DataGrid
之前的DataTable
的初始化创建的所有列。
解决方案2:
强制刷新ItemsSource
。它应该是这样的,但我强烈建议解决方法1如果可能的话:
var tempTable = oTable;
oTable = null;
RaisePropertyChanged("oTable");
oTable = tempTable;
RaisePropertyChanged("oTable");
请添加更多的信息([见MCVE(https://*.com/help/mcve))。除非我们知道发生了什么,否则很难提供帮助。 in'buildFromChildren' – grek40