WPF Binding to variable / DependencyProperty

前端 未结 2 519
灰色年华
灰色年华 2020-12-17 02:10

I\'m playing around with WPF Binding and variables. Apparently one can only bind DependencyProperties. I have come up with the following, which works perfectly fine: The cod

相关标签:
2条回答
  • 2020-12-17 02:50

    The CLR Property wrapper for a Dependency Property is never guaranteed to be called and therefore, you should never place any additional logic there. Whenever you need additional logic when a DP is changed, you should use the property changed callback.

    In your case..

    public string Test
    {
        get { return (string)this.GetValue(TestProperty); }
        set { this.SetValue(TestProperty, value); }
    }
    
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register("Test",
        typeof(string),
        typeof(MainWindow),
        new PropertyMetadata("CCC", TestPropertyChanged));
    
    private static void TestPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        MainWindow mainWindow = source as MainWindow;
        string newValue = e.NewValue as string;
        // Do additional logic
    }
    
    0 讨论(0)
  • 2020-12-17 02:59

    Your change will not affect the binding because the XAML will call SetValue directly, instead of calling your property setter.That is how the dependency property system works.When a dependency property is registered a default value can be specified.This value is returned from GetValue and is the default value for your property.

    Check the link below and read through to Robert Rossney's post to get a fair overview

    WPF: What distinguishes a Dependency Property from a regular CLR Property?

    also don't miss

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

    and

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

    Also note that unlike in normal CLR properties any custom logic you write in the setter will not be executed in Dependency Properties,instead you have to use the PropertyChangedCallback mechanism

    http://blogs.msdn.com/b/delay/archive/2010/03/23/do-one-thing-and-do-it-well-tip-the-clr-wrapper-for-a-dependencyproperty-should-do-its-job-and-nothing-more.aspx

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