如何从 DataTemplate 检索元素并绑定到它?
我试图在代码中获取 DataTemplate 中元素的句柄。我正在代码中创建一系列 DataGridTemplateColumns,然后将其分配给网格。 我希望能够从 xaml 中检索 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 并将其应用到数据网格。由于在向我提供源之前我不知道要绑定的属性,因此我无法创建嵌套在其自身内的 DataTemplate,该 DataTemplate 已内置此绑定。例如:
<TextBlock Text={Binding=LastName} ... >
所以我被迫在运行时创建一组 DataGridTemplateColumn ,在我的资源中查找 DataTemplate,然后尝试将该列绑定到我的数据源上的属性(如 LastName)。
I am trying to get a handle on an element within my DataTemplate in code. I am creating a series of DataGridTemplateColumns in code which I then assign to a grid.
I want to be able to retrieve the DataTemplate from the xaml, find my element and bind to that particular element.
Here is a short sample code what I am trying to achieve:
<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);
Maybe to explain this further:
I am trying to create a set of DataGridTemplateColumns on the fly and apply that to a Datagrid. Since I don't know the property to bind to until the time a source gets presented to me I cannot create a DataTemplate that nested within itself has this binding already build in. Like:
<TextBlock Text={Binding=LastName} ... >
So I am forced to create a set of DataGridTemplateColumn in runtime, look for DataTemplate in my resources and THEN try to bind that column to a property (like LastName) on my datasource.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会通过 CellStyle 来解决这个问题:
还有一些方法可以通过 DataTemplates 来做到这一点,但在这种情况下似乎没有必要(除非您的问题更复杂)。
I would approach this via CellStyle instead:
There are also ways to do this via DataTemplates but it does not seem necessary in this case (unless your problem is more complex).
我对这个问题的解决方案是这样的:
然后:
My solution to the problem is something like this:
and then: