简体   繁体   English

可以将View传递给MVVM中的ViewModel吗?

[英]Can Pass View to ViewModel in MVVM?

For my project I need to know which View is using my ViewModel 对于我的项目,我需要知道哪个View正在使用ViewModel

So i created this ViewModel: 所以我创建了这个ViewModel:

public class HistoriqueViewModel : INotifyPropertyChanged
{
   public HistoriqueViewModel(MetroWindow view)
    {
        this.MetroWindow = view;          
        this.ExportCommand = new RelayCommand(Export_Ex);          
    }

    private MetroWindow _metroWindow;
    public MetroWindow MetroWindow
    {
        get { return _metroWindow; }
        set
        {
            if (Equals(value, _metroWindow)) return;
            _metroWindow = value;
            OnPropertyChanged();
        } 
   } 
   //.........
 }     

And in the View constructor: 在View构造函数中:

 public partial class ViewHisto : MetroWindow
{
    public ViewHisto()
    {
        InitializeComponent();
        DataContext=new HistoriqueMV(this) ;
    }

 } 

It Work perfectly for me but I want to know if this Break the MVVM Pattern? 它对我来说很完美,但是我想知道这是否会打破MVVM模式吗?

Yes, this breaks MVVM. 是的,这会破坏MVVM。 A properly constructed view model shouldn't care about what the view is . 正确构造的视图模型不必在乎视图是什么

Nothing in your code really suggests why you are passing that reference (other than exposing the view as a public property, which is an even bigger no-no) but there are several ways around it: 您的代码中没有任何内容真正表明您为什么要传递该引用(除了将视图公开为公共财产外,这是更大的禁忌),但是有几种解决方法:

  • Pass the view as an interface and hold/expose that 将视图作为接口传递并保持/公开该视图
  • Use a mediator to pass whatever messages necessary between the view model/view 使用调解器在视图模型/视图之间传递任何必要的消息
  • Have the view invoke whatever methods it needs on the view model, and have the view model raise events that the view can listen to. 让视图调用视图模型上需要的任何方法,并让视图模型引发视图可以侦听的事件。

Any of the above approaches will provide far better decoupling than the one you are going with. 以上任何一种方法都将提供比您正在使用的方法更好的去耦。

One other thing, its "View Model", not "Model View" 另一件事,它的“视图模型”,而不是“模型视图”

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

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