Dynamically build a nested WPF DataGrid
I've found lots of code on this site and others that show how to create a nested datagrid in XAML but I'm unable to locate any information on how to use c# code to obtain the same results. What I would like to be able to do is convert this:
<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# code.
The data structure is something like this:
public class MessageData {
Guid MessageId {get; set;}
DateTime ReceivedDate { get; set; }
...
List<Even开发者_运维问答tDetail> Details { get; set; }
}
public class EventDetail {
Guid MessageId { get; set; }
DateTime LogDate { get; set; }
string LogEvent { get; set; }
...
}
It seems that now I can get most of it working except being able to define the columns in the inner datagrid - the code works if I set auto generate to true but I am unable to figure out how to define the columns for the inner grid.
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;
this works but when I set AutoGenerateColumns to false - and try to define the columns it fails...
Creating a DataGrid in code-behind is just a matter of doing the following:
var dataGrid = new DataGrid();
The DataGrid columns can be added in code-behind, see the following example 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);
Probably the trickiest part to do in code-behind is create your row template. The construction of DataTemplates in code has been covered in other questions:
Create DataTemplate in code behind
精彩评论