views:

395

answers:

2

Hi, I've created a WPF UserControl which contains a Button. I now want any consumer of the usercontrol to be able to set a Command property on the usercontrol, and for that command to be assigned to the button within the control. i.e. so that when the button is clicked, it runs the command (in this case a Prism DelegateCommand).

So, my UserControl looks like:

<UserControl>
  <Button ...>
</UserControl>

and my consumer, I wish to look like:

<controls:ThreeStateImageButtonControl
   Command="..." />
+2  A: 

You need to create a dependency property for Command on your control, then create an event handler for the button's Click event to execute Command. Then users can bind to Command. Perhaps a web tutorial or documentation would help you do that? Maybe google "WPF dependency property on user control tutorial" or some such thing.

However, I'm not sure you are doing the right thing. If your user control has nothing but a Button inside it, you may want to consider a custom control that inherits from Button instead; the implementation would be simpler, and users could just use the Click event in the normal way. There are also WPF custom control tutorials on the web in many places.

By the way, your property won't be actually called Command, right?

Patrick Szalapski
+1  A: 

C'mon man! It's WPF. The idea is to stay away from User Controls and Custom Controls, that's the old Windows Forms way of doing things. The best thing to do here is use WPF templating and the look-less features of WPF to style the control with the container and behaviors you like. Then you don't have to worry about passing through the Click or Command features since they're already there. Instead of wrapping a control in other elements and making it a User Control, just style your control with the other elements.

masenkablast
Thanks!, I suppose that is one approach worth considering. I think in this case, I'll make the control inherit from Button directly. The control may later have custom commands etc. If I implemented this as an explicit style, the commands would have to be redefined for each instance of the Button.
devdigital