Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically add events to buttons in XAML?

Tags:

c#

wpf

xaml

I am new to WPF/XAML so please bear with the noob question.

I have designed a control panel that will eventually function as a backend for my website, and have just finished laying out all the buttons in tabs using TabControl element. (this is designed using the Visual Studio 'Window' forms.

My question is, is it possible to create a function in the xaml.cs file that will dynamically handle a specific event for all my button elements ? for example...

I have 30+ buttons and dont want 30 different Click="btnCustomers_click" + their respective functions in the c# code. What I desire is say one function that would allow me to click any button and then open a new window depending on which button was selected.

The below code is my current design however for 30+ buttons their will be alot of functions and it will be messy, hence my desire to have one function control which window is opened depending on which button is clicked.

        private void btnMerchants_click(object sender, RoutedEventArgs e)
    {
        var newWindow = new frmMerchants();
        newWindow.Show();
    }

Thanks in advance for any advice given!! :)

like image 301
aaron Avatar asked Dec 27 '22 22:12

aaron


1 Answers

You could use a style for this:

<Style TargetType="{x:Type Button}">
    <EventSetter Event="Click" Handler="btnMerchants_click"/>
</Style>

If you set this up in the resources somewhere without an x:Key it will apply to all buttons.


e.g. if you have a Grid and you want a certain style to apply to all Buttons in it you would define it like this:

<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Button}">
            <EventSetter Event="Click" Handler="Button_Click"/>
        </Style>
    </Grid.Resources>
    <Grid.Children>
        <!-- Buttons and stuff -->
    </Grid.Children>
</Grid>

If you just want to apply it to some buttons set the x:Key and reference the style:

<Grid>
    <Grid.Resources>
        <Style x:Key="AttachClickHandlerStyle" TargetType="{x:Type Button}">
            <EventSetter Event="Click" Handler="Button_Click"/>
        </Style>
    </Grid.Resources>
    <Grid.Children>
        <Button Content="Click me!" Style="{StaticResource AttachClickHandlerStyle}"/>
        <Button Content="Click me, too!" Style="{StaticResource AttachClickHandlerStyle}"/>
        <Button Content="Something different." Click="SomeOtherButton_Click"/>
    </Grid.Children>
</Grid>

In general you should refactor any attributes that occur more than once into a style to prevent duplicate code.

Also, since you are a beginner the following articles might be of interest:

Styling and Templating
Resources Overview

like image 158
H.B. Avatar answered Jan 24 '23 12:01

H.B.