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

Sanjay Patel picture Sanjay Patel · Jan 9, 2013 · Viewed 49k times · Source

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?

Answer

nihique picture nihique · Jan 9, 2013

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()
    }
}