WPF依赖属性不起作用

Bob*_*Bob 9 .net c# vb.net wpf xaml

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

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

<controls:TargetCatalogControl MyCustomProperty="Boo" />
Run Code Online (Sandbox Code Playgroud)

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

小智 17

试试这个..

    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; }
    }
Run Code Online (Sandbox Code Playgroud)