C# 将DataTables列表绑定到datagrid的RowDetailsTemplate
我正在开发基于MVVM软件架构模式的wpf应用程序。 我有一个直接绑定到DataGrid的主DataTable。我有一个DataTables列表,每当单击DataGrid的一行时,我都希望显示它们。下面的代码是一个示例代码,只是为了了解它是如何完成的。我的实际项目遵循MVVM,我将在其中应用这个概念C# 将DataTables列表绑定到datagrid的RowDetailsTemplate,c#,wpf,mvvm,datagrid,datatable,C#,Wpf,Mvvm,Datagrid,Datatable,我正在开发基于MVVM软件架构模式的wpf应用程序。 我有一个直接绑定到DataGrid的主DataTable。我有一个DataTables列表,每当单击DataGrid的一行时,我都希望显示它们。下面的代码是一个示例代码,只是为了了解它是如何完成的。我的实际项目遵循MVVM,我将在其中应用这个概念 <Window x:Class="HierDataGrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006
<Window x:Class="HierDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate x:Key="Nested">
<ItemsControl ItemsSource="{Binding TableCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding TableCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataGrid RowDetailsTemplate="{StaticResource Nested}" ItemsSource="{Binding}" AutoGenerateColumns="True" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
CS文件
public partial class MainWindow : Window
{
public List<DataTable> TableCollection { get; set; }
public MainWindow()
{
InitializeComponent();
TableCollection = new List<DataTable>();
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
TableCollection.Add(table);
TableCollection.Add(table);
TableCollection.Add(table);
this.DataContext = this;
}
}
我可以直接将列表绑定到数据网格,但不能作为datagrid中RowDetailsTemplate的模板,当单击该行时,什么都没有。好的,在尝试了一点之后,我能够解决它。问题在于DataTemplat中的绑定
<Window.Resources>
<DataTemplate x:Key="Nested">
<ItemsControl ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=TableCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</Window.Resources>
伟大的发现!您可以接受答案,并让其他人知道这可以解决上述问题。