WPF数据网格:如何获取单元格的绑定表达式?

5
我需要获取DataGridTextColumn中DataGrid单元格的绑定表达式。例如:
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>

我成功获取了与单元格相关联的TextBlock:

        var cell = dataGrid.GetCellCtrl<TextBlock>(dataGrid.CurrentCell);

并且单元格似乎是正确的。我可以调用。

        cell.SetValue(TextBlock.TextProperty, value);

更新单元格文本。在网格上似乎可以工作(数字已更新)。然而,过了一段时间后我意识到源未被更新。即使将UpdateSourceTrigger更改为PropertyChange也没有帮助。于是,我认为需要获取绑定表达式并显式调用UpdateSource。

        var bindingExpr = cell.GetBindingExpression(TextBlock.TextProperty);

但是bindingExpr总是为空。为什么呢?

编辑: 我遇到的原问题是,我可以获得单元格的绑定TextBlock,并设置TextBlock.TextProperty。然而,数据源并没有被更新。这是我试图解决的问题。


你好,你解决了这个问题吗? - mohammad jannesary
列的SortMemberPath默认包含绑定路径(这是启用按绑定属性排序的默认属性值)。这不是获取绑定路径的可靠和预期方式,并且在多个绑定或手动设置SortMemberPath时将无法工作。 - kiran
3个回答

7
DataGridTextColumn中,TextBox将不会有一个绑定表达式,因为列本身已经有了绑定。 DataGridTextColumn是从DataGridBoundColumn派生而来,后者使用BindingBase属性而非TextBlock.TextProperty。然而,Binding属性不是DependancyProperty,因此你需要使用普通的公共属性进行访问。
所以你需要进行一些类型转换,因为DataGridTextColumn中的Binding属性是BindingBase类型的。像这样做应该可以(未经测试):
var binding = (yourGrid.Columns[0] as DataGridBoundColumn).Binding as Binding;

3
谢谢你的快速回复。你的代码确实让我绑定了列,但是它并没有解决我的问题。我该如何获取单元格的绑定表达式?整个问题的关键在于调用BindingExpression.UpdateSource(),因为如果我设置TextBlock.Text,源数据不会被更新。 - newman
将列转换为DataGridBoundColumn,我犯了一个错误,加1分! - smile.al.d.way

0
你需要找到 TextBlock:
var textBlock = cell.FindVisualChild<TextBlock>();
BindingExpression bindingExpression = textBlock.GetBindingExpression(
  TextBlock.TextProperty);

FindVisualChild()的代码:

public static class DependencyObjectExtensions
{
    [NotNull]
    public static IEnumerable<T> FindVisualChildren<T>([NotNull] this DependencyObject dependencyObject)
        where T : DependencyObject
    {
        if (dependencyObject == null) throw new ArgumentNullException(nameof(dependencyObject));

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(dependencyObject, i);
            if (child is T o)
                yield return o;

            foreach (T childOfChild in FindVisualChildren<T>(child))
                yield return childOfChild;
        }
    }

    public static childItem FindVisualChild<childItem>([NotNull] this DependencyObject dependencyObject)
        where childItem : DependencyObject
    {
        if (dependencyObject == null) throw new ArgumentNullException(nameof(dependencyObject));

        foreach (childItem child in FindVisualChildren<childItem>(dependencyObject))
            return child;
        return null;
    }
}

-2

TextBox t = e.EditingElement as TextBox; string b= t.GetBindingExpression(TextBox.TextProperty).ResolvedSourcePropertyName;

文本框t = e.EditingElement as TextBox; 字符串b = t.GetBindingExpression(TextBox.TextProperty).ResolvedSourcePropertyName;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接