As AvaloniaUI for now do not have an EventSetter
like in WPF in styles. This package try to replicate the way EventSetter
of WPF work in AvaloniaUI.
Install the nuget
dotnet add package CodingSeb.Avalonia.EventSetter
For the designer
To make the EventSetter
recognized by the designer you need to add the following line somewhere it's called by the designer. Example in App.axaml.cs
GC.KeepAlive(typeof(Avalonia.Styling.EventSetter).Assembly);
This is an hack to force the designer to load the corresponding assembly. See issue 7200 and 250 of AvaloniaUI.
In MainWindow.axaml :
<StackPanel>
<TextBox />
<TextBox />
<TextBox />
<StackPanel.Styles>
<Style Selector="TextBox" >
<EventSetter Event="KeyDown" Handler="TextBox_KeyDown" />
</Style>
</StackPanel.Styles>
</StackPanel>
In MainWindow.axaml.cs (CodeBehind) :
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
// What you want to do on textbox key down
}
As Event
and Handler
properties on the EventSetter
are string intellisense do not work. You need to know the name of the event and the handler you want to use. also the handler must have the good signature in code behind.
As the subscribe and unsubscribe of the event is done with Reflection
it can be slow on a large set of StyleElements
Attached events are not supported for now.