【发布时间】: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 类型的属性。