如何获取数据网格列的绑定表达式

本文关键字:网格 绑定 表达式 数据网 数据 何获取 获取 | 更新日期: 2023-09-27 18:00:47

如何在WPF中获取DataGrid列的绑定表达式?

这是列的XAML:

<DataGridTextColumn x:Name="amountColumn" Header="Amount" Width="100"  
                    Binding="{Binding _Amount, StringFormat=c}" 
                    CellStyle="{StaticResource errorStyle}"/>

如何获取数据网格列的绑定表达式

我使用此代码获取数据网格中的所有绑定表达式:

private Collection GetAllBindingsInDatagrid(DataGrid dg)
{
    Collection bindings = new Collection();
    if (dg.ItemsSource != null) {
        foreach (object item in dg.ItemsSource) {
            DataGridRow row = dg.ItemContainerGenerator.ContainerFromItem(item);
            if (row != null) {
                foreach (BindingExpression binding in row.BindingGroup.BindingExpressions) {
                    bindings.Add(binding);
                }
            }
        }
    }
    return bindings;
}

EDIT:由于问题是获取列的"绑定表达式",它指的是绑定的单个实例,我认为目的是检查是否存在任何验证错误或其他什么,所以上面的函数迭代行。但是,如果需要列本身的通用"绑定"(例如,为了动态添加验证规则),则可以使用以下代码:

// first retrieve the Datagrid object as datagrid
DataGridTextColumn column = datagrid.FindName("amountColumn");
Binding binding = column.Binding;

BindingExpression对象位于TextBlock元素上,而不是列上。首先你需要一个手机。然后您可以搜索内部TextBlock:

var textBlock = cell.FindFirstVisualChild<TextBlock>();
BindingExpression bindingExpression = textBlock.GetBindingExpression(TextBlock.TextProperty);

FindFirstVisualChild():的代码

public static class DependencyObjectExtensions
{
    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 FindFirstVisualChild<childItem>([NotNull] this DependencyObject dependencyObject)
        where childItem : DependencyObject
    {
        if (dependencyObject == null) throw new ArgumentNullException(nameof(dependencyObject));
        return FindVisualChildren<childItem>(dependencyObject).FirstOrDefault();
    }
}

使用BindingExpression

BindingExpression bindingExpression = amountColumn.GetBindingExpression(DataGridTextColumn.BindingProperty);