代码之家  ›  专栏  ›  技术社区  ›  denahiro

DependencyProperty未写入派生类[重复]

  •  1
  • denahiro  · 技术社区  · 13 年前

    我正在使用WPF/XAML,并基于 window 打电话 container . 容器 具有名为的DependencyProperty CurrentElementProperty 链接到属性 CurrentElement 。我的问题是 set 从未从调用属性的方法 DerivedContainer 。如果我更改 typeof(Container) typeof(DerivedContainer) 在属性注册过程中,它被调用。我几乎可以肯定,我在注册过程中做错了什么。

    定义 Container

    class Container : Window
    {
        public static readonly DependencyProperty CurrentElementProperty = 
            DependencyProperty.Register(
                "CurrentElement",
                typeof(Element),
                typeof(Container),
                new FrameworkPropertyMetadata(
                    null,
                    FrameworkPropertyMetadataOptions.Inherits));
        public Element CurrentElement
        {
            get
            {
                return (Element)this.GetValue(Container.CurrentElementProperty);
            }
            set
            {
                this.SetValue(Container.CurrentElementProperty, value);
            }
        }
    }
    

    第个XAML,共个 派生容器 (我删除了标准的XML命名空间定义)

    <local:Container x:Class="ns.DerivedContainer"
                     xmlns:local="clr-namespace:ns">
      <local:Container.CurrentElement>
        <Element />
      </local:Container.CurrentElement>
    </local:Container>
    

    代码隐藏 派生容器

    public partial class DerivedContainer : Container
    {
        public DerivedContainer()
        {
            InitializeComponent();
        }
    }
    
    1 回复  |  直到 13 年前
        1
  •  3
  •   Kent Boogaart    13 年前

    我的问题是从来没有从DerivedContainer调用过属性的set方法

    这不是问题,这是意料之中的行为。WPF调用 SetValue 而不是直接通过包装。包装器在那里是为了方便其他客户端代码。如果在设置属性时需要执行某些操作,则需要在 DependencyProperty.Register 呼叫