WPF How to know the current button pressed among multiple buttons

前端 未结 4 1882
北荒
北荒 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.

提交回复
热议问题