WPF依赖属性无法正常工作

11

我有一个自定义依赖属性,定义如下:

public static readonly DependencyProperty MyDependencyProperty =
DependencyProperty.Register(
"MyCustomProperty", typeof(string), typeof(MyClass));

    private string _myProperty;
    public string MyCustomProperty
    {
        get { return (string)GetValue(MyDependencyProperty); }
        set
        {
            SetValue(MyDependencyProperty, value);
        }
    }

现在我尝试在XAML中设置该属性

<controls:TargetCatalogControl MyCustomProperty="Boo" />

但是,在DependencyObject中的 setter 没有被调用!当我将属性更改为普通属性而不是Dep Prop时,它会被调用。

3个回答

19

试试这个...

    public string MyCustomProperty
    {
        get 
        { 
            return (string)GetValue(MyCustomPropertyProperty); 
        }
        set 
        { 
            SetValue(MyCustomPropertyProperty, value); 
        }
    }

    // Using a DependencyProperty as the backing store for MyCustomProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyCustomPropertyProperty =
        DependencyProperty.Register("MyCustomProperty", typeof(string), typeof(TargetCatalogControl), new UIPropertyMetadata(MyPropertyChangedHandler));


    public static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        // Get instance of current control from sender
        // and property value from e.NewValue

        // Set public property on TaregtCatalogControl, e.g.
        ((TargetCatalogControl)sender).LabelText = e.NewValue.ToString();
    }

    // Example public property of control
    public string LabelText
    {
        get { return label1.Content.ToString(); }
        set { label1.Content = value; }
    }

1
难道不应该只使用“new UIPropertyMetadata(0)”就可以工作吗?我也遇到了同样的问题。为什么要手动分配实现的原因是什么? - Den
@Den 我有同样的问题。为每个控件中的项目创建常规和依赖属性似乎很愚蠢。 - Killnine
@Killnine页面64包含解释(WPF 4.5 Unleashed,只需单击“查看内部”-该章节可免费获取):http://www.amazon.co.uk/WPF-4-5-Unleashed-Adam-Nathan/dp/0672336979 - Den

2
“除非您手动调用它,否则不会更改。您可以在DependencyProperty构造函数调用中添加属性更改处理程序以便在属性更改时收到通知。”
“调用此构造函数:”

http://msdn.microsoft.com/en-us/library/ms597502.aspx

使用此构造函数创建的 PropertyMetadata 实例:

http://msdn.microsoft.com/en-us/library/ms557327.aspx

编辑:此外,您没有正确实现依赖属性。您的getset应分别使用GetValueSetValue,并且不应有一个类成员来存储该值。DP的成员名称也应为{PropertyName}Property,例如,如果注册的get/set和属性名称为MyCustomProperty,则成员名称应为MyCustomPropertyProperty。有关更多信息,请参见http://msdn.microsoft.com/en-us/library/ms753358.aspx
希望这可以帮助您。

嗨Kieren,在你的第一个链接中没有要调用的“构造函数”,它解释了“DependencyProperty.Register方法”,这就是我使用的内容。你发错链接了吗?在你的第二个链接中,它是关于PropertyChangedCallback的,这与解决我的问题有什么关系?我的Dep Prop Setter没有被调用,这就是我遇到的问题! - Bob
我指的是Register方法,而不是构造函数。Setter不应该被调用,你正在错误地使用DPs,并且必须遵循提供的链接中描述的模式。WPF不会调用你的setter,它将使用SetValue:你必须提供一个PropertyMetadata对象,其中包含一个处理程序,当WPF更改你的值时将被调用。 - Kieren Johnstone

1
也许您正在使用MVVM,并覆盖视图的DataContext?如果是这样,那么更改MyCustomProperty的事件将在原始DataContext上引发,而不是在新的ViewModel上引发。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接