将DataTable列表绑定到datagrid的RowDetailsTemplate

时间:2014-07-03 05:45:01

标签: c# wpf mvvm datagrid datatable

我正在开发基于MVVM软件架构模式的wpf应用程序。 我有一个主DataTable,我直接绑定到DataGrid。我有一个DataTable列表,我想在点击DataGrid行时显示它们。下面的代码是一个示例代码,只是为了理解它是如何完成的。我的实际项目遵循MVVM,我将在其中应用这个概念。

<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的模板,当单击该行时没有任何内容。

1 个答案:

答案 0 :(得分:0)

好的,经过尝试,我能够解决它。问题在于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>
相关问题