[英]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 (eg Styles.xaml) without using ResourceDictionary Code-Behind (eg Styles.xaml.cs), mainly because I want the Styles.xaml to just be there for styling. 我想帮助解决如何在不使用ResourceDictionary Code-Behind(例如Styles.xaml.cs)的情况下处理ResourceDictionary(例如Styles.xaml)中控件的事件,主要是因为我希望Styles.xaml能够用于样式化。
My scenario is, I have a Custom Page which uses a ResourceDictionary for DataTemplate styles (I am using a TemplateSelector). 我的方案是,我有一个自定义页面,它使用ResourceDictionary的DataTemplate样式(我使用的是TemplateSelector)。 However, the problem I am currently having is for handling events.
但是,我目前遇到的问题是处理事件。 For example:
例如:
I have this in my Styles.xaml : 我在我的Styles.xaml中有这个:
.
.
<Button Click="Button_Click"/>
.
And I declare this in the CustomPage.xaml.cs : 我在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 eg
另外,是否可以为每个页面提供不同的处理程序,例如
CustomPage2.xaml.cs: CustomPage2.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
// some different code from CustomPage.xaml.cs
}
Thank you! 谢谢!
The answer is simple: do not handle events such a way. 答案很简单:不要以这种方式处理事件。 Use bindings instead (especially, if you're using data templates).
改为使用绑定(特别是,如果您使用的是数据模板)。 Eg, for
Button
: 例如,对于
Button
:
<Button Command="{Binding MyCommand}">
where MyCommand
is a ICommand
-implemented instance from your data context. 其中
MyCommand
是来自数据上下文的ICommand
实现的实例。
If you're not familiar with data bindings in WPF, start read from here . 如果您不熟悉WPF中的数据绑定,请从此处开始阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.