我想在代码中的DataTemplate中获取一个元素的句柄。我在代码中创建一系列DataGridTemplateColumns,然后将其分配给网格。 我想能够从xaml中检索DataTemplate,找到我的元素并绑定到该特定元素。如何从DataTemplate中检索元素并绑定到它?
这里是一个简短的示例代码是什么我想实现:
<DataTemplate x:Key="dataTemplate">
<Grid TextBlock.Foreground="LightGreen" Background="Yellow">
<TextBlock x:Name="txt" />
</Grid>
</DataTemplate>
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Last Name";
Binding b = new Binding("LastName");
DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
TextBlock textBlock = dtemplate.FindName("txt", this);
textBlock.SetBinding(TextBlock.TextProperty, b);
col.CellTemplate = dtemplate;
grid.Columns.Add(col);
可能进一步解释这一点: 我试图在飞行中创建一组DataGridTemplateColumns的并将其应用于Datagrid。因为我不知道属性绑定到,直到源被呈现在我面前,我不能创建嵌套本身一个DataTemplate的时候有这种结合已经建立像:
<TextBlock Text={Binding=LastName} ... >
所以我不得不在运行时创建一组DataGridTemplateColumn,在我的资源中查找DataTemplate,然后尝试将该列绑定到我的数据源上的属性(如LastName)。
的DataTemplates只是说明,大公不包含对象的引用。但是您可以更改DataTemplate应用到的对象。 – vorrtex 2011-04-15 16:33:27
+1以前的评论。用你在这里写的代码的类型,你可能会解释一下大局吗?当我看到直接处理WPF中的UI元素的代码不包含在自定义控件中时,它通常会发出红色标记。 – 2011-04-17 03:22:32
感谢您的回应 - 我试图创建一组DataGridTemplateColumns'在飞行',而不是能够指定(并绑定他们!)他们在XAML。这意味着我必须能够在指定列后将该列绑定到我的数据源上的dp。 – Marcel 2011-04-17 06:29:27