【问题标题】:WPF Custom control and binding propertyWPF 自定义控件和绑定属性
【发布时间】:2019-04-10 11:38:15
【问题描述】:

我正在开发自定义 ListView。在这个范围内,我想定义一个自定义的 GridViewColumn,它有一个 CellBinding 属性,它本身就是一个 BindingBase。

这个属性是这样定义的:

public class GridViewColumn : System.Windows.Controls.GridViewColumn
{
    public static readonly DependencyProperty CellBindingProperty = DependencyProperty.RegisterAttached( "CellBinding", typeof( BindingBase ), typeof( GridViewColumn ),
            new PropertyMetadata( null, new PropertyChangedCallback( OnCellBindingChanged ) ) );

    public BindingBase CellBinding
    {
        get => (BindingBase)this.GetValue( CellBindingProperty );
        set => this.SetValue( CellBindingProperty, value );
    }...

在 xaml 编辑器中一切正常,并且该属性似乎被正确识别:

     <wpfTools:GridViewColumn Header="Titre2" SortProperty="B" CellAlignement="Right" CellBinding="{Binding B}"/>

但是当我想在运行时使用这个属性时,column.CellBinding 的结果总是为空。 请问,为什么?

【问题讨论】:

  • B 是什么?什么财产?你知道GridViewColumnDataContext是父DataContext不是“行/项目”DataContext
  • 除了混淆基本功能之外,您期望从中获得什么?如果您想增加绑定的诊断,请将此 xmlns 添加到您的窗口:xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase" 然后在您的绑定中添加:diag:PresentationTraceSources.TraceLevel=High 当您运行它会将信息泵入您的输出窗口。
  • 因为 B 为空或不存在...如果您设置父级的 DataContext 再次父级不是 ItemsSource,请在调试输出中查找 System.Windows.Data Error: 40 : BindingExpression path error: 'B' property not found on ...
  • 请注意,将 RegisterAttached 用于常规依赖属性(而不是附加属性)是错误的。请改用DependencyProperty.Register。除此之外,CellBinding 也可以是常规 CLR 属性而不是依赖属性,因为它不需要是可绑定的。您只需将 XAML 中的 Binding 分配 到 BindingBase 类型的属性。

标签: c# wpf binding


【解决方案1】:
如果应该将

CellBinding 设置为 BindingBase,则

CellBinding 不应该是一个依赖属性。

您应该将其实现为 CLR 属性,然后实现您的 GridViewColumn 类以根据需要将绑定应用于生成的单元格元素:

public class GridViewColumn : System.Windows.Controls.GridViewColumn
{
    private BindingBase _cellBinding;
    public BindingBase CellBinding
    {
        get => _cellBinding;
        set => _cellBinding = value;
    }
    //...
}

获取依赖属性的值会评估绑定,这不是您想要的 BindingBase 属性。

【讨论】:

  • 非常感谢。我现在更了解它的工作原理了。
猜你喜欢
  • 2015-06-03
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 2011-05-11
  • 2015-06-03
  • 2012-08-07
相关资源
最近更新 更多