簡體   English   中英

將DataTable綁定到DataGrid。 WPF MVVM

[英]Binding DataTable to DataGrid. WPF MVVM

我試圖在Datagrid上綁定數據表,以便能夠動態填充它。 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似乎正確填充:

調試時的DataTable

問題很可能與DataTable初始化有關, DataGrid將在設置新的ItemsSource時自動生成列,但在初始化后將列添加到基礎表時不會重新生成列。

解決方案1:

在將DataTable綁定到DataGrid之前,在DataTable初始化時創建所有列。

解決方案2:

強制刷新ItemsSource 它應該像這樣工作,但如果可能的話,我強烈推薦解決方案1:

var tempTable = oTable;
oTable = null;
RaisePropertyChanged("oTable");
oTable = tempTable;
RaisePropertyChanged("oTable");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM