WPF How to know the current button pressed among multiple buttons

前端 未结 4 1839
北荒
北荒 2020-12-15 13:24

I am having multiple buttons with contents 1, 2, 3, 4, 5... like this. All buttons are using same function on Click event.

相关标签:
4条回答
  • 2020-12-15 13:47

    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.

    0 讨论(0)
  • 2020-12-15 13:48

    You can get the content property using this in your function -

    string content = (sender as Button).Content.ToString();
    
    0 讨论(0)
  • 2020-12-15 13:50

    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.

    0 讨论(0)
  • 2020-12-15 14:02

    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)) {...}
    
    0 讨论(0)
提交回复
热议问题