我试图通过代码创建一个元素,并为它关联一个样式,同时也将它的EventSetter关联在一起,样式工作得很完美,但是当我试图运行这个函数时,它不起作用。
App.xaml
<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 "App“不包含"lbl_MouseLeftButtonUp”的设置,也找不到任何接受"App“类型的第一个参数的"lbl_MouseLeftButtonUp”扩展方法(是否缺少使用指令或程序集引用?)
对于正确的事件,也会发生同样的错误,如何在我的类中实现这两个方法,而不给出问题呢?
发布于 2018-08-02 19:34:46
通常,当无法从XAML访问方法时,就会得到Error CS1061。
最常见的情况是:
x:Class标记与类的实际名称不匹配Handler不匹配的方法的名称private类中使用base方法而不是protected查看XAML代码,您的类名是Learning.App。
<Application x:Class="Learning.App"但是声明事件处理程序的代码是ViewConfigAgendaDin。
public class ViewConfigAgendaDin您不能将事件处理程序放在任何地方,并期望编译器自行找到它们。因为处理程序是在App.xaml.cs中使用的,所以需要将事件处理程序移动到,这样就更好了。
如果需要它们在ViewConfigAgendaDin类中,可以在ViewConfigAgendaDin.xaml中定义Style,或者从App.xaml.cs调用ViewConfigAgendaDin.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轻松地将任何事件绑定到命令
https://stackoverflow.com/questions/51659165
复制相似问题