开发者

WPF Dependency Property not working

I have a custom Dependency Property defined like so:

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

    private s开发者_StackOverflow社区tring _myProperty;
    public string MyCustomProperty
    {
        get { return (string)GetValue(MyDependencyProperty); }
        set
        {
            SetValue(MyDependencyProperty, value);
        }
    }

Now I try set that property in XAML

<controls:TargetCatalogControl MyCustomProperty="Boo" />

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


Try this..

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


It doesn't, unless you call it manually. There's a property-changed handler you can add to the DependancyProperty constructor call to be notified of when the property changes.

Call this constructor:

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

With a PropertyMetadata instance created by this constructor:

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

EDIT: Also, you are not implementing the dependancy property correctly. Your get and set should use GetValue and SetValue respectively, and you should not have a class member to store the value. The member name of the DP should also be {PropertyName}Property, e.g. MyCustomPropertyProperty if the get/set and property name as registered is MyCustomProperty. See http://msdn.microsoft.com/en-us/library/ms753358.aspx for more information.

Hope that helps.


Maybe you are using MVVM, and overriding the DataContext of your View ?

If you do, then the event for changing MyCustomProperty will be raised on the original DataContext and not on the new ViewModel.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜