自定义控件wpf,支持调用控件方法支持MVVM模式
我正在 WPF 中编写一个自定义控件,并且该控件中有几个方法可供控件的用户调用。
虽然可以直接调用,但由于用户的请求,我希望能够以MVVM的方式调用该控件的方法。
经过研究,我认为我必须在我的控件上实现 ICommandSource。 MSDN 有一个例子,但我发现它对于我的情况来说过度设计了(或者可能是因为我根本不理解它!)。 我想要的只是让我的消费者通过命令调用我的方法,而不是将他们的调用代码放在视图的代码后面。
请提供一个简单的示例代码来实现这一点。谢谢。
I am writing a custom control in WPF, and i have a couple of methods in the control that the user of my control can invoke.
Although it can be invoked directly, due to requests from users, i want to enable the control's methods to be invoked in a MVVM manner.
After research, i take it i have to implement ICommandSource on my control.
The MSDN has an example but i find it too much over-engineered for my situation (or maybe because i don;t understand it at all!).
All i want is to let my consumers to call my method via a command rather than put their calling code in view's code behind.
Please advise with a simple sample code to implement this. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Blend SDK 中有一个 MethodInvoker 行为(如果我没记错的话),它允许您绑定到一个方法。这样您就不必实现 ICommand。
In the Blend SDK is a behavior MethodInvoker (if my memory serves correct) that allows you to bind to a method. That way you do not have to implement ICommand.
如果您有权反映 .NET 代码(或者您可以通过 download) 看看 MS 如何使用 ButtonBase 来实现这一点。是的,幕后有很多代码,但这是因为如果您要创建自定义控件,您应该考虑 RoutedEvents 和 Commands 的两种情况。
If you have access to reflect over the .NET code (or you can download the .NET source code via download) look into how MS does it with ButtonBase. Yes, there is a lot of code under the hood, but that's because if you're going to create a custom control you should account for both scenarios of RoutedEvents and Commands.