我试图通过我的代码创建一个元素并为其关联一个样式,还关联其EventSetter,该样式可以完美地工作,但是当我尝试运行该功能时,它不起作用。

应用程式

<Application x:Class="Learning.App"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="clr-namespace:Learning">
<Application.Resources>
    <Style TargetType="Label" x:Key="LabelTituloEstiloPadrao">
    <Setter Property="Background" Value="White" />
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="Margin" Value="40,20,0,0" />

<EventSetter Event="MouseLeftButtonUp" Handler="lbl_MouseLeftButtonUp"/>
<EventSetter Event="MouseRightButtonUp" Handler="lbl_MouseRightButtonUp"/>

    </Style>
    </ResourceDictionary>
</Application.Resources>
</Application>


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“应用”不包含以下设置
  “ lbl_MouseLeftButtonUp”,找不到任何“ lbl_MouseLeftButtonUp”
  扩展方法,它接受类型为“ App”的第一个参数(是否存在
  使用指令或程序集引用丢失?)


正确的事件也会发生相同的错误,我该如何在我使用该类的类中实现这两个方法而又不产生问题?

最佳答案

通常,当无法从XAML访问方法时,会收到错误CS1061。

最常见的情况是:


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




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

<Application x:Class="Learning.App"


但是在其中声明事件处理程序的代码为ViewConfigAgendaDin

public class ViewConfigAgendaDin


您不能将事件处理程序放在任何地方,并且希望编译器自己找到它们。由于处理程序是在App.XAML中使用的,因此您需要将事件处理程序移至App.xaml.cs,这将是一个很好的选择。

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

编辑:

例如:

ViewConfigAgendaDin.xaml:

<ViewConfigAgendaDin
    xmlns:v="clr-namespace:MY_NAMESPACE">
...
    <Label Tag="{Binding RelativeSource={RelativeSource AncestorType={x:Type v:ViewConfigAgendaDin}}}"
           Style="{StaticResource LabelTituloEstiloPadrao}"/>
...
</ViewConfigAgendaDin>


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轻松将任何事件绑定到命令

关于c# - 在App.xaml的EventSetter上获取错误CS1061,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51659165/

10-12 00:29
查看更多