【发布时间】:2020-01-30 23:02:03
【问题描述】:
在数据网格中,我需要一个单元格有时是只读的列
我使用的是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; }
这当然是DataGrid 中的ItemsSource,实际上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。
【问题讨论】: