【问题标题】:Getting binding expression out of a DataGridTemplateColumn's CellTemplate in code-behind在代码隐藏中从 DataGridTemplateColumn 的 CellTemplate 中获取绑定表达式
【发布时间】:2012-01-20 01:44:18
【问题描述】:

我正在寻找在后面的代码中从 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”。

任何提示将不胜感激。

【问题讨论】:

标签: wpf binding datagrid code-behind datagridtemplatecolumn


【解决方案1】:

首先,您必须到达 CellTemplate 中的 TextBlock。

实际上@blindmeis 的回答提供了一个线索,但我会尝试在示例中用不同的方法来解释。

例如,在后面的代码中,您尝试在 MouseDoubleClick 事件上到达 TextBlock 的对象。

您可以使用 e.OriginalSource 访问 TextBlock 对象;

然后,BindingOperations.GetBinding(.. , ..).Path.Path 将为您提供您要查找的内容...

var tb = (e.OriginalSource as TextBlock);
if (tb == null)
    return;

之后你可以使用第一种方式或第二种方式:

第一种方式(注意,第一个Path表达式前有问号):

var bindingPath = BindingOperations.GetBinding(tb, TextBlock.TextProperty)?.Path.Path;

第二种方式:

var binding = BindingOperations.GetBinding(tb, TextBlock.TextProperty);
if (binding == null)
    return;

var bindingPath = binding.Path.Path;

【讨论】:

    【解决方案2】:

    最好知道你想用路径值做什么。

    here 是对类似问题的回答。

    编辑: 太好了,我不久前写了一个 excel 转换器 :) 但我的版本不支持绑定点表示法和 TemplateColumns。 TemplateColumns 的问题是您不知道是否有 1 个或多个绑定以及可视化树的外观。也许在第一步中,您可以沿着模板列的可视化树走到第一个绑定并获取它。

    【讨论】:

    • 您好,blindmeis,我正在为 DataGrids 编写一个 excel 导出文件,并且我正在使用绑定值,但我无法获取所有模板列的值。
    • 对于普通列,我通过以下方式获取值: if (gridColumn is DataGridBoundColumn) { Binding binding = ((DataGridBoundColumn)gridColumn).Binding as Binding; }
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 2014-04-10
    • 2013-08-08
    相关资源
    最近更新 更多