Of-course, the more automated and lazier the better.
So a few tips:
You can generate a new event handler with an automated name like this:
- Assign the
x:Name before creating or assigning the event handler
Pick the default <New Event Handler> from the list of options IDE gives you for your event handler. it will generate something like:
MouseDoubleClick="mButton_MouseDoubleClick"
or Click="mButton_Click"
If the name is already taken, it will be prefixed with _1
If the x:Name is not assigned, it will be prefixed with Button_ instead of x:Name
You can generate any already-written event handler like this:
- Right click on handler's name in XAML code (
"mClick") and choose Go To Definition (The default shortkey is F12)
F12 does the same thing as double-clicking on an event handler value in properties window in WinForms. In case of default event (like Button's Click, it does the same as double-clicking directly on the control)
If you don't want the control to contain any code for event handler like:
<Button /> // handles the click event magically
Then you can add this to the container of all the buttons:
<Container.Resources>
<Style TargetType="Button">
<EventSetter Event="Click" Handler="mClick"/>
</Style>
</Container.Resources>
(obviously, I supposed the name of the container is Container. In your case it might be Window or Menu etc.)
Now every button inside this container has its Click handled by the same handler, in which you can redirect your logic to the right method:
Dictionary<string, Action> dic;
private void mClick(object sender, RoutedEventArgs e)
{
dic[(sender as Button).Name]();
}
These all still so tedious compared to MVVM pattern:
<ItemsControl ItemsSource="{Binding myButtons}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding ButtonText}" Command="{Binding ButtonAction}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>