DataGrid嵌套DataGrid(也叫主从表),效果为:单击表中某项后,从中间展开一个新表,总表绑定的是题目类大集合,从表绑定的是对应的选项集合.
第一:选构建题目类,再建一个选项类,题目类集合中的每个项包含一个选项类集合,即数组嵌套数组,C#语句如下:
(为方便看清语句,类直接写在主程序中)
C#代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Collections .ObjectModel ;//ObservableCollection命名空间 namespace DataGridInDataGrid { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } //题目类 class question { public Int32 questionID//题目ID号 { get; set; } public string questionName//题目名,比如:第1题或第2题等 { get; set; } public ObservableCollection<choseItem> choseItems//某题中"选项类"的集合,比如A-D { get; set; } public question(Int32 _id, string _questionname, ObservableCollection<choseItem> _choseitems)//构造函数 { questionID =_id ; questionName = _questionname; choseItems = _choseitems; } } //选项类 class choseItem { public string ChoseName//选项名,比如:A,B,C,D之类 { get; set; } public string ChoseContent//选项内容 { get; set; } } ObservableCollection<question> Questions = new ObservableCollection<question>();//题目数组 private void Window_Loaded(object sender, RoutedEventArgs e) { string[] CharStr = new string[4] { "A", "B", "C", "D" }; for (int i = 0; i < 5; i++) { ObservableCollection<choseItem> ChoseItems = new ObservableCollection<choseItem>();//选项数组 for (int j = 0; j < 4; j++) { choseItem item = new choseItem();//选项类 item.ChoseName = CharStr[j] + ":"; item.ChoseContent = "选项内容举例..."; ChoseItems.Add(item); } Questions.Add(new question(i,"__第" + (i + 1).ToString() + "题", ChoseItems)); } datagrid1.ItemsSource = Questions; } } }
第二步:主界面的绑定语句如下:
主界面代码
<Window x:Class="DataGridInDataGrid.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="DataGridInDataGrid" Height="350" Width="525" Loaded="Window_Loaded"> <Grid> <DataGrid AutoGenerateColumns="False" Name="datagrid1"> <DataGrid.Columns> <DataGridTextColumn Header="ID值" IsReadOnly="True" Width="auto" Binding="{Binding questionID}" /> <DataGridTextColumn Header="题目" IsReadOnly="True" Width="auto" Binding="{Binding questionName}" /> </DataGrid.Columns> <DataGrid.RowDetailsTemplate > <DataTemplate > <DataGrid ItemsSource="{Binding choseItems}" AutoGenerateColumns="False" Margin="30,20,0,20" Background="Green"> <DataGrid.Columns> <DataGridTextColumn Header="选项名" Binding="{Binding ChoseName}" /> <DataGridTextColumn Header="选项内容举例" Binding="{Binding ChoseContent}"/> </DataGrid.Columns> </DataGrid> </DataTemplate> </DataGrid.RowDetailsTemplate> </DataGrid> </Grid> </Window>
第三:小结一下
1:表嵌套表也叫主从表,主要用到了DataGrid.RowDetailsTemplate 行详细模板,
2:要注意被嵌套的表要设置好margin值,要不然一点开会很突然,用户都搞不懂在显示什么,