Use Dependency Property to pass a callback method

7.1k views Asked by At

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

There are 1 answers

2
Olaru Mircea On

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.