Reputation: 119
I have a WPF Window with many buttons (btn_1, btn_2, btn_3 ... btn_81) and instead to create a click-event for each button like this:
private void btn_1_Click(object sender, RoutedEventArgs e)
{
if (backColor != null)
btn_1.Background = backColor;
}
private void btn_2_Click(object sender, RoutedEventArgs e)
{
if (backColor != null)
btn_2.Background = backColor;
}
I meant to create only one click-event and get somehow the name of the button I clicked to perform the action. The action performed with the click-event is for each button the same: they must change their background.
I hope I could explain my issue. TIA!
Upvotes: 1
Views: 1879
Reputation: 6203
Just add same event to each button. In your case add btn_1_Click
. You can do that like:
btn1.Click += btn1_Click;
btn2.Click += btn1_Click;
btn3.Click += btn1_Click;
...
or
btn1.Click += new EventHandler(btn1_Click);
btn2.Click += new EventHandler(btn1_Click);
btn3.Click += new EventHandler(btn1_Click);
...
private void btn1_Click(object sender, RoutedEventArgs e)
{
// do something
}
Upvotes: 4
Reputation: 1251
In your XAML you can bind the buttons click events to the same handler:
<StackPanel>
<Button Content="btn1" x:Name="btn1" Click="btn_Click"></Button>
<Button Content="btn2" x:Name="btn2" Click="btn_Click"></Button>
<Button Content="btn3" x:Name="btn3" Click="btn_Click"></Button>
</StackPanel>
And the code behind:
Brush backColor = new SolidColorBrush(Colors.Red);
private void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
if (btn != null && backColor != null)
btn.Background = backColor;
}
Upvotes: 5
Reputation: 59
you can do
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
if (Equals(sender, bt1))
{
}
else if(Equals(sender, bt2))
{
}
}
xaml
<Button Content="Button 1" Name="bt1" Click="ButtonBase_OnClick"/>
<Button Content="Button 2" Name="bt2" Click="ButtonBase_OnClick"/>
Upvotes: 0