【发布时间】:2013-12-19 13:29:03
【问题描述】:
我正在尝试以编程方式为 DataGrid 创建一个数据模板。 我能够这样做。但我被困在一个位置。 DataGrid 的绑定不起作用。 我认为绑定存在一些问题。这是我得到的输出:
图像中的第 3 列是空的,尽管我已经为该列设置了绑定。
这是 XAML 文件:
<Window x:Class="NestedListViewDemo.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" WindowState="Maximized">
<Grid Name="MainGrid">
<DataGrid x:Name="myDataGrid" AutoGenerateColumns="true" Loaded="myDataGrid_Loaded">
<DataGrid.Columns>
<DataGridTemplateColumn x:Name="templatecolumnId" Header="Id" />
<DataGridTemplateColumn x:Name="templatecolumnName" Header="Name" />
<DataGridTemplateColumn x:Name="templateColumnInnerTable" Header="InnerTable" />
</Datagrid.Columns>
</DataGrid>
</Grid>
</Window>
我添加了三列,并在第三列中尝试以编程方式添加另一个数据网格。 这是代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataGrid innergrid = new DataGrid();
InnerClass ic=new InnerClass();
ic.InnerData="InnerXYZ";
innergrid.Items.Add(ic);
AddressClass ac = new AddressClass();
ac.Id = "1";
ac.Name = "XYZ";
ac.setDatagrid(innergrid);
myDataGrid.Items.Add(ac);
myDataGrid.MinRowHeight = 100;
myDataGrid.MinColumnWidth = 250;
}
public void myDataGrid_Loaded(object sender, EventArgs e)
{
var dataTemplate = new DataTemplate();
FrameworkElementFactory tbHolder1 = new FrameworkElementFactory(typeof(Label));
tbHolder1.SetBinding(Label.ContentProperty, new Binding("Id"));
dataTemplate.VisualTree = tbHolder1;
dataTemplate.DataType = typeof(DataGridTemplateColumn);
templatecolumnId.CellTemplate = dataTemplate;
dataTemplate = new DataTemplate();
FrameworkElementFactory tbHolder2 = new FrameworkElementFactory(typeof(TextBlock));
tbHolder2.SetBinding(TextBlock.TextProperty, new Binding("Name"));
dataTemplate.VisualTree = tbHolder2;
dataTemplate.DataType = typeof(DataGridTemplateColumn);
templatecolumnName.CellTemplate = dataTemplate;
dataTemplate = new DataTemplate();
FrameworkElementFactory tbHolder3 = new FrameworkElementFactory(typeof(DataGrid));
tbHolder3.SetBinding(DataGrid.DataContextProperty, new Binding("Address"));
tbHolder3.SetValue(DataGrid.AutoGenerateColumnsProperty, true);
dataTemplate.VisualTree = tbHolder3;
dataTemplate.DataType = typeof(DataGridTemplateColumn);
templateColumnInnerTable.CellTemplate = dataTemplate1;
}
public class AddressClass
{
public string Id { get; set; }
public string Name { get; set; }
private DataGrid address;
public DataGrid Address
{
get { return address; }
}
public void setDatagrid(DataGrid dtnew)
{
this.address = dtnew;
}
}
public class InnerClass
{
public string InnerData{ get; set; }
}
}
【问题讨论】:
-
你为什么在代码后面做所有这些事情?这就是 XAML 的用途。
-
我想做的就是创建 n 级的嵌套 ListView/DataGrid。级别是在运行时决定的。因此,我想到了在后面的代码中执行此操作。
标签: c# wpf data-binding datagrid