简体   繁体   English

使用MVVM模式在自定义控件或UserControl上调用方法的正确方法?

[英]Proper way to call method on custom Control or UserControl with MVVM pattern?

I'm using PRISM and MVVM in my modular Silverlight application. 我在模块化Silverlight应用程序中使用PRISM和MVVM。 I'm still trying to figure out PROPER way to do interactions in MVVM fashion and 2 methods that PRISM and samples offer is not something I like for different reasons. 我仍在尝试找出以MVVM方式进行交互的正确方法,而PRISM和示例提供的2种方法由于不同的原因我都不喜欢。

Method 1(PRISM): To use different region adapter. 方法1(PRISM):使用不同的区域适配器。 Basically, it involves attached properties on container and injecting view into region. 基本上,它涉及容器上的附加属性并将视图注入区域。 This works almost 100% but negative of this method is that there is no good way to communicate results back. 这几乎可以100%起作用,但是此方法的缺点是没有好的方法可以将结果传递回去。 I can use EventAggregator but something doesn't feel right to raise event with data when interaction completed. 我可以使用EventAggregator,但是在交互完成后,某些事情不适合使用数据引发事件。

Method 2(PRISM): To use InteractionRequest. 方法2(PRISM):使用InteractionRequest。 That involves trigger action and some big boilerplate XAML that I have to repeat on each view. 这涉及触发操作和一些我必须在每个视图上重复的大型XAML。

I'm thinking on creating something on my own which would require creating my own control which will have to be added to each view but with very little XAML and some kind of IPopupService that I can bind this control to. 我正在考虑自己创建一些东西,这将需要创建自己的控件,该控件必须添加到每个视图中,但是需要很少的XAML和可以绑定到该控件的某种IPopupService。 I can pass all needed data via PopupService but in order to actually make action of POPUP happen - I need to call method on this control and that falls apart in MVVM 我可以通过PopupService传递所有需要的数据,但是为了使POPUP实际发生,我需要在此控件上调用方法,而这在MVVM中会分崩离析

I wonder how to call method on control in MVVM where view shouldn't be aware of VM ? 我想知道如何在视图中不应该知道VM的MVVM中的控件上调用方法?

View has no option but be aware of VM, since it binds to it. View除了与VM绑定外,别无选择,但请注意VM。

You could define some kind of a service indeed with a run-time implementation that would interact with the UI and design/test/debug implementation that does something else. 您可以使用运行时实现来定义某种服务,该实现将与UI交互,并执行其他功能的设计/测试/调试实现。 You might also publish some events in your VM layer that the View layer would decide how to interpret. 您可能还会在VM层中发布一些事件,View层将决定如何解释这些事件。

First off, I don't think MVVM is a good choice if you are developing a UserControl that will be consumed by others. 首先,如果您正在开发将由其他用户使用的UserControl,我认为MVVM不是一个不错的选择。 A lookless control is what you really should be developing. 一个无表情的控件是您真正应该开发的。 Jeremiah Morrill has a blog post about this subject. 耶利米·莫里尔(Jeremiah Morrill)对此主题发表了一篇博客文章。

With that said, you can set the datacontext with XAML if you have a default public constructor. 话虽如此,如果您具有默认的公共构造函数,则可以使用XAML设置数据上下文。

Inside ControlView.xaml put: 在ControlView.xaml内部放:

<UserControl.DataContext>
    <local:ControlViewModel />
</UserControl.DataContext>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM