WPF How to know the current button pressed among multiple buttons
If you place Name
or x:Name
attributes in your XAML for your buttons, you can then use the native object.Equals() without having to cast or dereference. This also protects you from having to double edit your code, and possibly forgetting to edit in both places when the Content
of the control is changed.
Given
<Button Name="btnOne" ... /><Button Name="btnTwo" ... />
then
if (sender.Equals(btnOne)) {...}if (sender.Equals(btnTwo)) {...}
Use the attribute x:Name is good in almost case
it would be better if you use x:Name attribute in your XAML.
For example, if you use x:Name in XAML, it would be perfect with your source code.
<Button x:Name="BtnA" Content="Some Btn A" Click="TestBtn_Click"></Button><Button x:Name="BtnB" Content="Some Btn B" Click="TestBtn_Click"></Button>
And then you can get this object in .cs file by type BtnA and BtnB.
private void TestBtn_Click(object sender, RoutedEventArgs e) {if(sender.Equals(BtnA)) { //User click BtnA to trigger TestBtn_Click()} else if (sender.Equals(BtnB)) { //User click BtnB to trigger TestBtn_Click()} else { //trigger TestBtn_Click() by another reason.}
Through x:Name attribute, your .cs file can select any element in XAML by it.