2017-08-30 83 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> 

私の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); 
      } 
     } 
    } 

と、これはグラフィカルな表現である:

Datagrid

しかし、私はそれをデバッグするときのDataTableを正しく満たしているようだ:

DataTable when debugging

+0

((https://stackoverflow.com/help/mcve)[MCVEを参照])より多くの情報を追加してください。私たちが何が起こるかを知るまで助けがたいです。 'buildFromChildren'にあります。 – grek40

答えて

1

問題はおそらくDataTable初期化に関連して、新しいItemsSourceが設定されている場合DataGridが列を自動生成しますが、それは再ません。 - 初期化後に基になるテーブルに列が追加されたときに列を生成します。

解決方法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

関連する問題