我想綁定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似乎正確填寫:
請添加更多的信息([見MCVE(https://stackoverflow.com/help/mcve))。除非我們知道發生了什麼,否則很難提供幫助。 in'buildFromChildren' – grek40