Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i access a control in mvvm model in viewmodel?

I have a WPF Window, and in that window I have a grid.

I use M-V-VM model and I want to add a TextBox to the grid dynamically in code(in viewmodel)

How can I get access to the grid?

like image 684
Sanjay Patel Avatar asked Jan 09 '13 13:01

Sanjay Patel


People also ask

Can we pass view to ViewModel?

As you can see, if we want to display more than one Model into a single View, we have to pass a ViewModel to that View, so that we can take benefits of both the models into a single object. So, we have to use ViewModel for better performance of sources.

What is the use of ViewModel in MVVM?

The purpose of ViewModel is to encapsulate the data for a UI controller to let the data survive configuration changes. For information about how to load, persist, and manage data across configuration changes, see Saving UI States.


2 Answers

Use Supervising Controller pattern.

Reading:

Example implementation for CaliburnMicro MVVM framework is shown here (will work same for all other frameworks - or you can do it by hand if you are doing MVVM by yourself):

http://drc.ideablade.com/devforce-2012/bin/view/Documentation/cocktail-tutorial-talk-to-view

Example:

1) Define interface IView in which ViewModel (VM) will talk to View with the required method(s)

public interface IView  {     void AddTextBoxToGrid(); } 

2) Inherit code behind View from your IView and implement IView.AddTextboxToGrid() method

public partial class View: IView  {     public void AddTextBoxToGrid()      {           // implement here your custom view logic using standard code behind;      } } 

3) Add a property of type IView to your VM

public class ViewModel  {     public IView View { get; set; } } 

4) Set View property on VM to an instance of View as IView e.g. in code behind:

 DataContext.View = this as IView;  

or in Caliburn you can use IScreen.OnViewAttached override method)

public partial class View: IView  {     public View()     {         // access you VM by the strategy of your framework or choice - this example is when you store your VM in View's DataContext         (DataContext as ViewModel).View = this as IView;     }       public void AddTextBoxToGrid()      {           // implement here your custom view logic using standard code behind;      } } 

5) In your VM call IView.AddTextboxToGrid()

public class ViewModel  {     public IView View { get; set; }      public void AddTextBoxToGrid()      {         if (View == null) return;         View.AddTextBoxToGrid()     } } 
like image 194
nihique Avatar answered Sep 28 '22 04:09

nihique


You should move your creation code to View, and ViewModel should just notify view when it should be called.

like image 43
Lonli-Lokli Avatar answered Sep 28 '22 05:09

Lonli-Lokli