bloodfire1004
bloodfire1004

Reputation: 503

How to handle events from ResourceDictionary without using ResourceDictionary Code-Behind?

I would like help regarding how to handle events from controls in a ResourceDictionary (e.g. Styles.xaml) without using ResourceDictionary Code-Behind (e.g. Styles.xaml.cs), mainly because I want the Styles.xaml to just be there for styling.

My scenario is, I have a Custom Page which uses a ResourceDictionary for DataTemplate styles (I am using a TemplateSelector). However, the problem I am currently having is for handling events. For example:

I have this in my Styles.xaml:

.
.
<Button Click="Button_Click"/>
.

And I declare this in the CustomPage.xaml.cs :

private void Button_Click(object sender, RoutedEventArgs e)
{
  // some code
}

However, it does not work. Is there any way to explicitly tell that I want to use that particular Event Handler for the button's click event? Additionally, is it possible to have different handlers for each page e.g.

CustomPage2.xaml.cs:

private void Button_Click(object sender, RoutedEventArgs e)
{
   // some different code from CustomPage.xaml.cs
}

Thank you!

Upvotes: 0

Views: 1696

Answers (1)

Dennis
Dennis

Reputation: 37780

The answer is simple: do not handle events such a way. Use bindings instead (especially, if you're using data templates). E.g., for Button:

<Button Command="{Binding MyCommand}">

where MyCommand is a ICommand-implemented instance from your data context.

If you're not familiar with data bindings in WPF, start read from here.

Upvotes: 2

Related Questions