【问题标题】:Binding IsReadOnly property of DataGridColumn depending on row根据行绑定 DataGridColumn 的 IsReadOnly 属性
【发布时间】: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}}"

VisibilityBinding 的绑定按预期工作。
Data 是视图模型的 DataContextAnotherProp 是它的属性之一。

视图模型还具有属性public ObservableCollection&lt;MyItem&gt; MyItems { get; private set; } 这当然是DataGrid 中的ItemsSource,实际上Binding 绑定到每行的每个MyItem 的属性。

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

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

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

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 1970-01-01
      • 2012-08-01
      • 2013-07-25
      • 2010-10-14
      • 2012-10-04
      • 2014-01-03
      • 2019-04-04
      • 2014-03-31
      相关资源
      最近更新 更多