如何处理ResourceDictionary中的事件而不使用ResourceDictionary Code-Behind? [英] How to handle events from ResourceDictionary without using ResourceDictionary Code-Behind?

查看:482
本文介绍了如何处理ResourceDictionary中的事件而不使用ResourceDictionary Code-Behind?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要帮助关于如何处理ResourceDictionary(例如Styles.xaml)中的控件的事件,而不使用ResourceDictionary Code-Behind(例如Styles.xaml.cs),主要是因为我希望Styles.xaml只是在那里对于样式来说,

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.

我的场景是,我有一个自定义页面,它使用DataDictionary作为DataTemplate样式(我使用的是TemplateSelector)。但是,我目前遇到的问题是处理事件。例如:

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:

我在我的 Styles.xaml 中有:

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

我在 CustomPage.xaml.cs 中声明: p>

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
}

谢谢!

推荐答案

答案很简单:不要这样处理事件。使用绑定(特别是如果您使用数据模板)。例如按钮

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}">

其中 MyCommand 是一个 ICommand 从数据上下文中实现的实例。

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

如果您不熟悉WPF中的数据绑定,请从 here

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

这篇关于如何处理ResourceDictionary中的事件而不使用ResourceDictionary Code-Behind?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆