我正在尝试在Datagrid上绑定Datatable以便能够动态填充它。 Datagrid似乎找到了Datatable,因为当我填充它并且在RaisePropertyChanged之后我有很多空行。也没有专栏。
我的观点:
<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似乎正确填充:
答案 0 :(得分:1)
问题很可能与DataTable
初始化有关,DataGrid
会在设置新的ItemsSource
时自动生成列,但是当列为时,它不会重新生成列初始化后添加到基础表。
解决方案1:
在DataTable
初始化之前创建所有列,然后将其绑定到DataGrid
。
解决方案2:
强制刷新ItemsSource
。它应该像这样工作,但如果可能的话,我强烈推荐解决方案1:
var tempTable = oTable;
oTable = null;
RaisePropertyChanged("oTable");
oTable = tempTable;
RaisePropertyChanged("oTable");