bluefox
bluefox

Reputation: 175

WPF UserControl generic click event

I have created a UserControl in WPF which consists of 2 simple buttons in the first run.

Now, I want to display in a MessageBox the x:Name of the button which is clicked by the user, but I don't want to create a Clicked event for each button separately.

Is it possible to program 1 generic Clicked event in the UserControl and then identify the sender object to get the correct x:Name ?

Upvotes: 0

Views: 918

Answers (2)

mm8
mm8

Reputation: 169200

Is it possible to program 1 generic Clicked event in the UserControl and then identify the sender object to get the correct x:Name ?

Sure:

<Button x:Name="first" Click="generic_Click" />
<Button x:Name="second" Click="generic_Click" />

private void generic_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = sender as Button;
    MessageBox.Show(clickedButton.Name);
}

Upvotes: 4

XAMlMAX
XAMlMAX

Reputation: 2363

Use an EventSetter for that in a style for a button.
Example in xaml:

<StackPanel
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SDKSample.EventOvw2"
Name="dpanel2"
Initialized="PrimeHandledToo"
>
<StackPanel.Resources>
    <Style TargetType="{x:Type Button}">
        <EventSetter Event="Click" Handler="b1SetColor"/>
    </Style>
</StackPanel.Resources>
<Button>Click me</Button>
<Button Name="ThisButton" Click="HandleThis">
    Raise event, handle it, use handled=true handler to get it anyway.
</Button>
</StackPanel>  

And then in cs file:

void b1SetColor(object sender, RoutedEventArgs e)
{
    Button b = e.Source as Button;
    b.Background = new SolidColorBrush(Colors.Azure);
}

void HandleThis(object sender, RoutedEventArgs e)
{
    e.Handled=true;
}

Upvotes: 0

Related Questions