首页 > 解决方案 > 根据行绑定 DataGridColumn 的 IsReadOnly 属性

问题描述

在数据网格中,我需要一列,其单元格有时是只读的

我使用 bindingproxy 方法:

<local:MyDataGrid.Resources>
     <local:BindingProxy x:Key="proxy" Data="{Binding}" />
</local:MyDataGrid.Resources>

其中 Data 是自定义的 DependencyProperty

public object Data
{
    get { return (object)GetValue(DataProperty); }
    set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. 
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy),  
                          new UIPropertyMetadata(null));

在 xaml 我有:

<DataGridCheckBoxColumn Header="MyProp"
    IsReadOnly="{Binding MyProp.IsReadOnly, Source={StaticResource proxy}"
    Binding="{Binding MyProp.MyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    Visibility="{Binding Data.AnotherProp, Source={StaticResource proxy}, Converter={StaticResource BoolToVisibilityConverter}}"

Visibility和的绑定Binding按预期工作。
Data是视图模型的DataContext并且AnotherProp是它的属性之一。

视图模型还具有public ObservableCollection<MyItem> MyItems { get; private set; } 当然是 的属性,ItemsSource并且DataGrid确实Binding绑定到MyItem每行的每个单个的属性。

但是,这不适用于IsReadOnly绑定。我应该怎么做才能让它工作?
BindingExpression 路径错误:在对象 BindingProxy 上找不到“MyProp”属性。
这是可以理解的,因为MyProp不属于Data
但是为什么绑定Binding工作呢?

当然也IsReadOnly="{Binding Data.MyProp.IsReadOnly, Source={StaticResource proxy}}"不起作用,因为MyProp它是视图模型的属性MyItem而不是视图模型的属性。

没有绑定代理也IsReadOnly="{Binding MyProp.IsReadOnly}"不起作用。
找不到目标元素的管理 FrameworkElement 或 FrameworkContentElement。

标签: wpfdatagrid

解决方案


Binding属性很特别。它的类型是BindingBase,它用于将绑定应用到在GenerateElement方法中创建的元素,即您并没有真正将此属性绑定到源属性。您宁愿将其设置为Binding对象。

如果要绑定到IsReadOnly,则需要像绑定到Visibility属性时一样使用代理。


推荐阅读