9

I have a user control with several buttons, which need to take different actions depending on the class using it.

The problem is that I don't know how to implement those handlers because when using my user control from the final app I don't have direct access to the buttons to specify which handler handles which events.

How would you do that?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
M Rajoy
  • 4,028
  • 14
  • 54
  • 111

2 Answers2

21

Another way to do this is to expose the events through events in your UserControl :

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }


    public event RoutedEventHandler Button1Click;

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        if (Button1Click != null) Button1Click(sender, e);     
    }
}

This gives your usercontrol a Button1Click event that hooks up to that button within your control.

J...
  • 30,968
  • 6
  • 66
  • 143
4

I would create a command for each button and delegate for each "handler". Than you can expose delegates to the user (final app) and internally call them on Execute() method on the commands. Something like this:

public class MyControl : UserControl {
        public ICommand FirstButtonCommand {
            get;
            set;
        }
        public ICommand SecondButtonCommand {
            get;
            set;
        }
        public Action OnExecuteFirst {
            get;
            set;
        }
        public Action OnExecuteSecond {
            get;
            set;
        }

        public MyControl() {
            FirstButtonCommand = new MyCommand(OnExecuteFirst);
            FirstButtonCommand = new MyCommand(OnExecuteSecond);
        }
    }

Of cource, "MyCommand" needs to implement ICommand. You also need to bind your commands to coresponding buttons. Hope this helps.

Vale
  • 3,258
  • 2
  • 27
  • 43