Use Dependency Property to pass a callback method

血红的双手。 提交于 2019-12-10 10:14:40

问题


I am using the Jarloo's calendar control in order to display a calendar in my WPF software. For my needs, I added that each day contains a list of items, lets say List<Item> Items.

The Jarloo calendar is a second project within my main visual studio solution. I am using this control this way :

<Jarloo:Calendar DayChangedCallback="{Binding DayChangedEventHandler}"/>

As you can see, I wish I could pass a method from my main project to the calendar's project so that I can, within the Calendar's constructor, add the method as a eventhandler of the DayChanged event.

However, the item received through the dependency is null...

In the calendar code, my dependency property is defined as :

public static readonly DependencyProperty DayChangedCallbackProperty = DependencyProperty.Register("DayChangedCallback", typeof(EventHandler<DayChangedEventArgs>), typeof(Calendar));

My "DayChangedEventHandler" is defined as

public EventHandler<DayChangedEventArgs> DayChangedHandler { get; set; }
void DayChanged(object o, DayChangedEventArgs e)
{
}

// i set this way the DayChangedHandler property so that I can bind on it from the view
DayChangedHandler = new EventHandler<DayChangedEventArgs>(DayChanged);

Does someone has a hint for me?

Thanks a lot :) .x


回答1:


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.



来源:https://stackoverflow.com/questions/30939209/use-dependency-property-to-pass-a-callback-method

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