2017-08-30 175 views
2

我想綁定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); 
      } 
     } 
    } 

,這是圖形渲染:

Datagrid

但是,當我調試它的DataTable似乎正確填寫:

DataTable when debugging

+0

請添加更多的信息([見MCVE(https://stackoverflow.com/help/mcve))。除非我們知道發生了什麼,否則很難提供幫助。 in'buildFromChildren' – grek40

回答

1

該問題最有可能涉及到DataTable初始化,DataGrid將自動生成列時,新的ItemsSource設置,但不會重新 - 在初始化後將列添加到基礎表時生成列。

解決方案1:

它綁定到DataGrid之前的DataTable的初始化創建的所有列。

解決方案2:

強制刷新ItemsSource。它應該是這樣的,但我強烈建議解決方法1如果可能的話:

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

THX BRO。這是解決方案。我沒有想到這一點。你救了我的一天! – Ant4r

+0

@ Ant4r沒問題。如果這解決了你的問題,你應該接受答案:https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – grek40