WPF依赖项属性不起作用 [英] WPF Dependency Property not working

查看:65
本文介绍了WPF依赖项属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的Dependency属性,定义如下:

I have a custom Dependency Property defined like so:

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中设置该属性

Now I try set that property in XAML

<controls:TargetCatalogControl MyCustomProperty="Boo" />

但是DependencyObject中的setter永远不会被击中!尽管当我将属性更改为常规属性而不是Dep Prop

But the setter in DependencyObject never gets hit! Although it does when I change the property to be a regular property and not a Dep Prop

推荐答案

尝试一下..

    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; }
    }

这篇关于WPF依赖项属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆