I'm trying to create an element by my code and associate a style for it, also associating its EventSetter, the style works perfectly but when I try to run the function it does not work.
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");
}
when the application is being built, two errors are fired into the EventSetter
Error CS1061 "App" does not contain a setting for "lbl_MouseLeftButtonUp" and could not find any "lbl_MouseLeftButtonUp" extension method that accepts a first argument of type "App" (is there a usage directive or assembly reference missing?)
The same error also happens for the right event, how can I do to implement these two methods in my class where I am using this without giving problems?
Generally, you get Error CS1061 when a method is inaccessible from XAML.
Most common cases are:
x:Class
tag not matching the actual name of the classHandler
of event setterprivate
method in thebase
class instead ofprotected
Looking at the XAML code, your class name is
Learning.App
But the code behind in which the event handlers are declared is
ViewConfigAgendaDin
You can't put the event handlers anywhere and expect the compiler to find them by itself. Because the handler is used in
App.XAML
, you need to Move the event handlers toApp.xaml.cs
and it will be good to go.If you need them to be in
ViewConfigAgendaDin
class, either define theStyle
inViewConfigAgendaDin.xaml
or call a method inViewConfigAgendaDin.xaml.cs
fromApp.xaml.cs
Edit:
For example:
ViewConfigAgendaDin.xaml:
ViewConfigAgendaDin.xaml.cs:
App.xaml.cs:
Another way to handle this situation is to avoid code-behind altogether. Instead, make use of MVVM and Command Binding. You can easily bind any event to a command using Interactions