WPF UserControl 通用点击事件

WPF UserControl generic click event

我在 WPF 中创建了一个 UserControl,它由第一个 运行 中的 2 个简单按钮组成。

现在,我想在 MessageBox 中显示用户单击的按钮的 x:Name,但我不想为每个按钮单独创建一个 Clicked 事件。

是否可以在 UserControl 中编写 1 个通用 Clicked 事件,然后识别 sender 对象以获得正确的 x:Name

在按钮样式中使用 EventSetter
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>  

然后在cs文件中:

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;
}

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

当然可以:

<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);
}