【问题标题】:Binding can only be set on a DependencyProperty of a DependencyObject - when property is overridden with new绑定只能在 DependencyObject 的 DependencyProperty 上设置 - 当属性被 new 覆盖时
【发布时间】:2012-04-19 15:34:00
【问题描述】:

我有一个如下的类层次结构,并且绑定到 VisibleRange 属性正在设计器中。

鉴于这里的类层次结构:

// Base class
public 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 class
public class DateTimeAxis : AxisBase
{
        public new IRange<DateTime> VisibleRange
        {
            get { return (IRange<DateTime>)GetValue(VisibleRangeProperty); }
            set { SetValue(VisibleRangeProperty, value); }
        }
}

// And interface definitions
public interface IRange<T> : IRange 
{
}

这里是设计师(XAML):

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

我得到了这个例外:

不能在“DateTimeAxis”类型的“VisibleRange”属性上设置“绑定”。 “绑定”只能在 DependencyObject 的 DependencyProperty 上设置。

派生类DateTimeAxis 公开了被new 关键字覆盖的VisibleRange 属性。我无法将通用类型参数添加到基类 AxisBase 中,而且我还需要访问这两个类中的属性。所以,我想知道考虑到这些限制,是否有人对如何更好地避免设计器异常有任何建议?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    “依赖属性”是您注册的东西:

     public static readonly DependencyProperty VisibleRangeProperty = 
        DependencyProperty.Register("VisibleRange", typeof(IRange), typeof(AxisBase), ...);
    

    当您查看该语句时,您可以看到它正在注册 typeof(IRange)

    派生类 DateTimeAxis 公开了被 new 关键字覆盖的 VisibleRange 属性。

    是的,但它公开的是“正常”属性,而不是依赖属性。
    另一个因素是属性具有不同的类型。

    【讨论】:

    • 它暴露了基础的 DependencyProperty - 我想这是它出错的地方吧?我可能可以使用新的覆盖并在整个代码中进行强制转换
    • 是的,DP是奇怪的野兽。我会绕过这个。
    【解决方案2】:

    尝试在你的XAxis的代码初始化中写,比如

    AxisBase XAxis = new DateTimeAxis ()

    应该工作。

    【讨论】:

    • 不确定你的意思 - DateTimeAxis 是在 Xaml 中构造的,而不是 C# 代码
    • 我的意思是对象的 actual 类型可能是基本类型,但 real 是子类型之一。在这种情况下,绑定可能是,可能会因为依赖属性不存在于真实对象类型中,而是存在于其基础类型中这一事实而变得模糊不清。只是一个猜测,我只是好奇它是否有效。没试过的别打扰,有时间我会试试的。
    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 2021-07-16
    • 2017-10-30
    • 1970-01-01
    • 2019-05-02
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多