【问题标题】:How to handle events from ResourceDictionary without using ResourceDictionary Code-Behind?如何在不使用 ResourceDictionary Code-Behind 的情况下处理来自 ResourceDictionary 的事件?
【发布时间】:2012-09-13 06:31:16
【问题描述】:

我需要有关如何在不使用 ResourceDictionary Code-Behind(例如 Styles.xaml.cs)的情况下处理来自 ResourceDictionary(例如 Styles.xaml)中控件的事件的帮助,主要是因为我希望 Styles.xaml 就在那里用于造型。

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

我的 Styles.xaml 中有这个:

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

我在 CustomPage.xaml.cs 中声明了这一点:

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

但是,它不起作用。有什么方法可以明确告诉我想为按钮的点击事件使用那个特定的事件处理程序?此外,是否可以为每个页面设置不同的处理程序,例如

CustomPage2.xaml.cs:

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

谢谢!

【问题讨论】:

  • 输出窗口有错误吗?
  • 不。实际上,我不是在寻找正确的语法,因为它们只是简单的代码 sn-ps。我只是在寻找如何实现它的方法,因为目前,我所拥有的不是方法,也不起作用。

标签: c# wpf event-handling resourcedictionary


【解决方案1】:

答案很简单:不要以这种方式处理事件。请改用绑定(尤其是在您使用数据模板的情况下)。例如,对于Button

<Button Command="{Binding MyCommand}">

其中MyCommand 是您的数据上下文中的ICommand 实现实例。

如果您不熟悉 WPF 中的数据绑定,请从 here 开始阅读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多