2011-09-08 67 views
0

このサイトおよびXAMLでネストされたデータグリッドを作成する方法を示したコードが多数見つかりましたが、同じコードを取得するためのC#コードの使用方法に関する情報は見つかりません結果。私ができるようにしたいのは、これを次のように変換することです:動的にネストされたWPF DataGridを構築する

<DataGrid ...> 
    <DataGrid.Columns> 
    <DataGridTextColumn Header="Received Date" Binding="{Binding Received}" .../> 
    ... 
    </DataGrid.Columns> 
    <DataGrid.RowDetailsTemplate> 
    <DataTemplate> 
     <DataGrid ItemsSource="{Binding Details}" ...> 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Log Date" Binding="{Binding LogDate}" /> 
       ... 
      </DataGrid.Columns> 
     </DataGrid> 
     </DataTemplate> 
    </DataGrid.RowDetailsTemplate> 
    <DataGrid> 

to C#のコードです。コードは、私が自動生成した場合に動作します -

public class MessageData { 
    Guid MessageId {get; set;} 
    DateTime ReceivedDate { get; set; } 
    ... 
    List<EventDetail> Details { get; set; } 
} 

public class EventDetail { 
    Guid MessageId { get; set; } 
    DateTime LogDate { get; set; } 
    string LogEvent { get; set; } 
    ... 
} 

それは今、私はそれのほとんどが内部データグリッドの列を定義することができることを除いて働いて得ることができるようです:

データ構造は、このようなものですしかし、私は内側のグリッドの列を定義する方法を理解することができません。

DataGrid dg = new DataGrid(); 
... 
dg.IsReadOnly = true; 
FrameworkElementFactory details = FrameworkElementFactory(typeof(DataGrid)); 
details.SetBinding(ItemsControl.ItemsSourceProperty, new Binding("Details")); 
details.SetValue(DataGrid.AutoGenerateColumnsProperty, true); 
DataTemplate dt = new DataTemplate(typeof(DataGrid)); 
dt.VisualTree = details; 
dt.RowDetailsTemplate = dt; 
dg.ItemsSource = myDataSouce; 

この作品が、私はfalseにAutoGenerateColumnsを設定したときに - と、それが失敗した列を定義しようとする...コードビハインドでデータグリッドを作成

答えて

1

だけで次の操作を行うの問題です:

var dataGrid = new DataGrid(); 

データグリッド列はコードビハインドで添加することができ、以下の例from MSDN参照:

//Create a new column to add to the DataGrid 
DataGridTextColumn textcol = new DataGridTextColumn(); 
//Create a Binding object to define the path to the DataGrid.ItemsSource property 
//The column inherits its DataContext from the DataGrid, so you don't set the source 
Binding b = new Binding("LastName"); 
//Set the properties on the new column 
textcol.Binding = b; 
textcol.Header = "Last Name"; 
//Add the column to the DataGrid 
DG2.Columns.Add(textcol); 

おそらくコードビハインドで最も難しいのは、行テンプレートを作成することです。コード内DataTemplatesの建設は、他の質問でカバーされています:

Create DataTemplate in code behind

+0

私はDataTemplateのものを持っている - しかし、私が知って投げていただきました外のデータグリッドと... –

+0

はなぜべきinnergrid間のデータバインディングですそのバインディングは何か難しいですか? 'AncestorType = {x:Type DataGrid} 'の' RelativeSource'検索でネストとネストされたデータグリッドのリンクができませんか? –

関連する問題