Pass WPF Button Command through UserControl

2019-06-13 08:16发布

问题:

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="..." />

回答1:

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?



回答2:

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.