I am having multiple buttons with contents 1, 2, 3, 4, 5... like this. All buttons are using same function on Click event.
I tend to deal with this problem by attaching an object to the button's tooltip property. You can then get it back like this:
void EditMe(object sender, RoutedEventArgs e) { Button x = sender as Button; if (x != null) { int id = (x.ToolTip as TT).Id; } }
The TT object in this example looks like:
public class TT { public int Id { get; set; } public string Text { get; set; } public override string ToString() { return Text; } }
Which displays the tooltip text on the UI and makes the Id accessible in the click handler.
You can get the content property using this in your function -
string content = (sender as Button).Content.ToString();
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.
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)) {...}