在代码隐藏中从 DataGridTemplateColumn 的 CellTemplate 中获取绑定表达式
我正在寻找一种可能性,可以在后面的代码中从 DataGridTemplateColumn 的 CellTemplate 中读取绑定表达式。 我的模板列如下所示:
<DataGridTemplateColumn x:Name="..." Header="...">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=City}" Style="..."/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ... />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
现在我想获取数据模板中绑定路径的值。在这种情况下,我喜欢获取值“City”。
任何提示将不胜感激。
I'm looking for a possibility to read the binding expression out of a DataGridTemplateColumn's CellTemplate in code behind.
My template columns look like this:
<DataGridTemplateColumn x:Name="..." Header="...">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=City}" Style="..."/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ... />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
Now I want to get the value of the binding path in the datatemplate. In this case, I'like to get the value "City".
Any tips would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须到达 CellTemplate 内的 TextBlock。
实际上@blindmeis的答案给出了一个线索,但我会尝试在示例中用不同的方法进行解释。
例如,在后面的代码中,您尝试在 MouseDoubleClick 事件上访问 TextBlock 的对象。
您可以使用 e.OriginalSource 到达 TextBlock 对象;
然后,BindingOperations.GetBinding(.. , ..).Path.Path 将为您提供您要查找的内容...
之后您可以使用第一种方式或第二种方式:
第一种方式(注意。第一个前面有一个问号路径表达式):
第二种方式:
First, you have to reach the TextBlock inside the CellTemplate.
Actually @blindmeis' answer is giving a clue but I'll try to explain with different approach in a sample.
In code behind, for instance, you try to reach the object that TextBlock on MouseDoubleClick event.
You can reach TextBlock object using e.OriginalSource;
Then, BindingOperations.GetBinding(.. , ..).Path.Path will give you what are you looking for...
After that you can use first way or second way:
First way (Attention. There is a question mark before first Path expression) :
Second way:
最好知道你想用路径值做什么。
这里是一个答案类似的问题。
编辑:
太好了,我不久前写了一个 Excel 转换器:),但我的版本不支持绑定点符号和 TemplateColumns。 TemplateColumns 的问题是您不知道是否有 1 个或多个绑定以及可视化树的外观。也许第一步中,您可以沿着模板列的可视化树走到第一个绑定并获取它。
it would be good to know what you wanna do with the path value.
here is an answer to a similar question.
EDIT:
thats nice i wrote an excel converter a while back :) but my version does not support Binding dot notation and TemplateColumns. the problem with TemplateColumns is that you dont know if the have 1 or more binding and how the visual tree look like. maybe in a first step you can walk down the visual tree of your template column to the first binding and take it.