2
votes

I have a View1 with a DataGrid in it and have set the View1.DataContext = ViewModel1. The ViewModel1 has a ObservableCollection<Dto> that I have bound to the DataGrid's ItemSource. Now, I have another View2 with a set of checkboxes and a ViewModel2 as its DataContext. I have to set the Visibility of the column's in DataGrid in View1 based on the ViewModel2 properties. I am new to WPF and dont know if this right to do and how to achieve it.

2

2 Answers

0
votes

As the name implies a ViewModel should contain all the data needed to display the view. You should put the visibility flag from ViewModel2 as a property in the ViewModel1 so that all the information needed to display View1 are present in ViewModel1.

Following this path your code will be simpler to maintain and it works without any special handling with the default behavior of View1.DataContext. If your ViewModel1 depends on ViewModel2 your View1 also depend on ViewModel2. This may be not a problem if you only have 2 ViewModels. But as soon as your application grows you will have many more ViewModels and if you keep depending them on each other your application will be unmaintainable in a very short time.

0
votes

You can expose your ViewModel2 in your ViewModel1 here is an example

public class ViewModel1
{
   public ViewModel2 {get;set;}
   public ViewModel1()
   {
      this.ViewModel2 = new ViewModel2(); //or you can send  ViewModel2 instance as a parameter
   }
} 

now you can set the DataContext as the following

  1. set View1 DataContext to ViewModel1
  2. set View2 DataContext to ViewModel1.ViewModel2
  3. in your View2 you do the binding to the check boxes as you are doing it now
  4. in your View1 you bind the Visibility of a column such as {Binding ViewModel2.someproperty}

if ViewModels need to know things about each other you need to consider one of the following

  • ChildView Models
  • using an EventAggregator.
  • Having a ViewModel that contains the ViewModels that need to know things about each other and handling things that they have to react about with PropertyChanged event
  • or simply making a single ViewModel that contains all properties, and you set the DataContext of your View1 and View2 to that ViewModel