1

For my project I need to know which View is using my ViewModel

So i created this 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:

 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?

Nadir Mezhoudi
  • 155
  • 2
  • 13

1 Answers1

4

Yes, this breaks 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"

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117