通过 UserControl 传递 WPF 按钮命令 [英] Pass WPF Button Command through UserControl

查看:40
本文介绍了通过 UserControl 传递 WPF 按钮命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个包含按钮的 WPF UserControl.我现在希望用户控件的任何使用者都能够在用户控件上设置 Command 属性,并将该命令分配给控件中的按钮.也就是说,当按钮被点击时,它会运行命令(在本例中为 Prism DelegateCommand).

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).

所以,我的 UserControl 看起来像:

So, my UserControl looks like:

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

和我的消费者,我希望看起来像:

and my consumer, I wish to look like:

<controls:ThreeStateImageButtonControl
   Command="..." />

推荐答案

您需要为控件上的 Command 创建一个依赖属性,然后为按钮的 Click 事件创建一个事件处理程序以执行 Command.然后用户可以绑定到命令.也许网络教程或文档可以帮助您做到这一点?也许谷歌用户控制教程上的 WPF 依赖属性"或类似的东西.

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.

但是,我不确定您是否在做正确的事情.如果你的用户控件里面只有一个 Button,你可能需要考虑一个继承自 Button 的自定义控件;实现会更简单,用户可以正常使用 Click 事件.网上很多地方也有WPF自定义控件教程.

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.

顺便说一下,您的属性实际上不会被称为 Command,对吗?

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

这篇关于通过 UserControl 传递 WPF 按钮命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆