具有CellTemplate和绑定的自定义DataGrid列 [英] Custom DataGrid column with a CellTemplate and binding
问题描述
我需要使用自定义CellTemplate创建可重用的DataGrid列。除其他事项外,此CellTemplate应该包含一个TextBlock控件,我需要将其绑定到要显示在DataGrid中的值。到目前为止,我看到的所有示例都在DataGrid的Columns属性中使用时直接为列指定了CellTemplate,还直接指定了对TextBlock的绑定,例如:
I need to create a reusable DataGrid column with a custom CellTemplate. This CellTemplate should, among other things, contain a TextBlock control to which I need to bind values to display in the DataGrid. All examples I've seen so far specified the CellTemplate for a column directly when using it in a DataGrid's Columns property and also specified a Binding directly to the TextBlock, e.g.:
<data:DataGrid>
<data:DataGrid.Columns>
<data:DataGridTemplateColumn Header="Name">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
</data:DataGrid.Columns>
</data:DataGrid>
我需要将此列封装为单个可重用的控件,并且我想为其指定一个绑定就像普通的DataGridTextColumn一样。换句话说,使用此自定义列时,我只想编写如下内容:
I need to encapsulate this column into a single, reusable control and I want to specify a Binding for it just like for an ordinary DataGridTextColumn. In other words, when using this custom column, I just want to write something like this:
<data:DataGrid>
<data:DataGrid.Columns>
<controls:CustomColumn Header="Name" Binding="{Binding Name}" />
</data:DataGrid.Columns>
</data:DataGrid>
问题是自定义列继承的DataGridTemplateColumn不具有Binding属性。我以为我可以使用DataGridBoundColumn,但是无法为其指定CellTemplate。
Problem is that the DataGridTemplateColumn my custom column is inheriting from does not have the Binding property. I thought that I will be able to use DataGridBoundColumn, but it's not possible to specify a CellTemplate for it.
如何实现所需的行为?谢谢!
How to achieve a desired behavior? Thank you!
推荐答案
我认为最简单的方法是创建一个customcontrol然后按如下方式使用它:
I think the simplest thing to do is to create a customcontrol then use it like this:
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<controls:CustomColumn Header="Name" Binding="{Binding Name}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
昨天我做了类似的事情,而且效果很好
I did something similar yesterday, and it works pretty well
这篇关于具有CellTemplate和绑定的自定义DataGrid列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!