在App.xaml的EventSetter上获取错误CS1061

我正在尝试通过我的代码创建一个元素并为其关联一个样式,同时关联它的EventSetter,样式完美地工作但是当我尝试运行该函数时它不起作用。

App.xaml中

            

MainWindow.xaml.cs

 public ViewConfigAgendaDin() { InitializeComponent(); ConfigInicial(); Label l = new Label(); lblTeste.Style = (Style)App.Current.Resources["LabelTituloEstiloPadrao"]; StackHorarios.Children.Add(l); } private void lbl_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { MessageBox.Show("Right"); } public void lbl_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { MessageBox.Show("Left"); } 

在构建应用程序时,会向EventSetter中触发两个错误

错误CS1061“App”不包含“lbl_MouseLeftButtonUp”的设置,并且找不到任何“lbl_MouseLeftButtonUp”扩展方法,该方法接受“App”类型的第一个参数(是否缺少使用指令或程序集引用?)

对于正确的事件也会发生同样的错误,我怎样才能在我的类中实现这两个方法,而不是给出问题?

通常,当XAML无法访问某个方法时,会出现Error CS1061

最常见的情况是:

  • 事件处理程序未在代码隐藏中声明
  • XAML的x:Class标记与x:Class的实际名称不匹配
  • 与事件设置器的Handler不匹配的方法的名称
  • 错误的论点
  • base类中使用private方法而不是protected
  • 在极少数情况下需要重新启动visual studio

查看XAML代码,您的类名是Learning.App

  

但是声明事件处理程序的代码是ViewConfigAgendaDin

 public class ViewConfigAgendaDin 

您不能将事件处理程序放在任何位置,并希望编译器自己找到它们。 因为在App.XAML使用了处理程序, App.XAML需要将事件处理程序移动到App.xaml.cs ,这样会很好。

如果您需要它们在ViewConfigAgendaDin类中,请在ViewConfigAgendaDin中定义Style或从App.xaml.cs调用ViewConfigAgendaDin.xaml的方法

编辑:

例如:

ViewConfigAgendaDin.xaml:

  ...  ...  

ViewConfigAgendaDin.xaml.cs:

 public void MyMethodForRightClick(object sender, MouseButtonEventArgs e) { MessageBox.Show("Right"); } 

App.xaml.cs:

 private void lbl_MouseRightButtonUp(object sender, MouseButtonEventArgs e) { ((sender as Label).Tag as ViewConfigAgendaDin).MyMethodForRightClick(sender, e); } 

处理这种情况的另一种方法是完全避免代码隐藏。 相反,请使用MVVM命令绑定。 您可以使用Interactions轻松地将任何事件绑定到命令