wpf - 根据行绑定 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。
解决方案
Binding
属性很特别。它的类型是BindingBase
,它用于将绑定应用到在GenerateElement
方法中创建的元素,即您并没有真正将此属性绑定到源属性。您宁愿将其设置为Binding
对象。
如果要绑定到IsReadOnly
,则需要像绑定到Visibility
属性时一样使用代理。
推荐阅读
- python - numpy.roots 背后的数学
- react-native - 如何在渲染前修改数组
- error-handling - 无法处理 django-rest-framework 上的响应错误
- python - 使用 BeautifulSoup 从文本文件中获取 URL
- mysql - 为什么仅在强制而不是默认情况下才使用索引?
- excel - VBA 不复制整行,缺少一列
- assembly - 我们如何判断堆栈帧当前是空的?
- vue.js - 如何从 window.open() 函数链接到 vue 的构建文件夹(dist)?
- python - 关于在 Python 上检查字符类型的问题
- algorithm - 如何在列表中加入具有相同值的字符串列表