C# · 12月 26, 2021

c# – 绑定只能在DependencyObject的DependencyProperty上设置 – 当使用new覆盖属性时

@H_502_1@我有一个类层次结构,如下所示,绑定到VisibleRange属性是在设计器中抛出.

鉴于此处的类层次结构:

// Base classpublic abstract class AxisBase : ContentControl,IAxis{ public static readonly DependencyProperty VisibleRangeProperty = DependencyProperty.Register( “VisibleRange”,typeof(IRange),typeof(AxisBase),new PropertyMetadata(default(IRange),OnVisibleRangeChanged)); public IRange VisibleRange { get { return (IRange)GetValue(VisibleRangeProperty); } set { SetValue(VisibleRangeProperty,value); } }}// Derived classpublic class DateTimeAxis : AxisBase{ public new IRange<DateTime> VisibleRange { get { return (IRange<DateTime>)GetValue(VisibleRangeProperty); } set { SetValue(VisibleRangeProperty,value); } }}// And interface deFinitionspublic interface IRange<T> : IRange {}@H_301_5@

和设计师(XAML)在这里:

<local:DateTimeAxis Style=”{StaticResource XAxisStyle}” VisibleRange=”{Binding ElementName=priceChart,Path=XAxis.VisibleRange,Mode=TwoWay}”/>@H_301_5@

我得到这个例外:

A ‘Binding’ cannot be set on the ‘VisibleRange’ property of type ‘DateTimeAxis’. A ‘Binding’ can only be set on a DependencyProperty of a DependencyObject.

派生类DateTimeAxis公开VisibleRange属性,该属性被new关键字覆盖.我不能将通用类型参数添加到基本AxisBase类,我还需要访问这两个类中的属性.所以,我想知道给定这些约束,如果有人有任何建议如何更好地避免设计师异常?

解决方法 “依赖属性”是您注册的内容: public static readonly DependencyProperty VisibleRangeProperty = DependencyProperty.Register(“VisibleRange”,…);@H_301_5@

当你看那个陈述时,你可以看到它正在注册typeof(IRange)

The derived class DateTimeAxis is exposing the VisibleRange property which is overridden by the new keyword.

是的,但它暴露了“正常”属性,而不是依赖属性.另一个因素是属性具有不同的类型.