Use Dependency Property to pass a callback method

独自空忆成欢 提交于 2019-12-06 00:06:20

Here is an example regarding your non-static field issue:

public partial class MainWindow : Window
{
   public bool IsChecked
   {
       get { return (bool)GetValue(IsCheckedProperty); }
       set { SetValue(IsCheckedProperty, value); }
   }

// Using a DependencyProperty as the backing store for IsChecked.  This enables animation, styling, binding, etc...
   public static readonly DependencyProperty IsCheckedProperty =
    DependencyProperty.Register("IsChecked", typeof(bool), typeof(MainWindow), new PropertyMetadata(false, new PropertyChangedCallback(PropertyChanged)));


   private static void PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
   {
       MainWindow localWindow = (MainWindow)obj;
       Console.WriteLine(localWindow.TestString);
    }

   public string TestString { get; set; }

    public MainWindow()
    {
       InitializeComponent();

       TestString = "test";
       this.DataContext = this;
    }
}

And here is the XAML to test it:

<CheckBox Content="Case Sensitive" IsChecked="{Binding IsChecked}"/>

When the property is changed, the callback is called and in thix example, you can access the non static TestString property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!