Dependency Property assigned with value binding does not work

后端 未结 2 1618
暗喜
暗喜 2020-12-30 07:09

I have a usercontrol with a dependency property.

public sealed partial class PenMenu : UserControl, INotifyPropertyChanged
{
    public event PropertyChanged         


        
相关标签:
2条回答
  • 2020-12-30 07:34

    The getter and setter of a dependency property are not guaranteed to be run, and in particular the WPF binding engine / XAML processor is documented to bypass these. Have a look on MSDN - the getter/setter should just be a wrapper around GetValue/SetValue on the DependencyProperty itself.

    Instead of reacting in the setter of your property, you should add a property changed handler in the original call to DependencyProperty.Register, when you can act on the new value.

    (see other questions).

    0 讨论(0)
  • 2020-12-30 07:42

    It's frustrating isn't it? First, include a changed event handler. Like this:

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }
    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), 
        typeof(MyControl), new PropertyMetadata(string.Empty, Changed));
    private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var c = d as MyControl;
        // now, do something
    }
    

    Then, please read this article so you see there are more gotchas than just that one: http://blog.jerrynixon.com/2013/07/solved-two-way-binding-inside-user.html

    Best of luck!

    0 讨论(0)
提交回复
热议问题