Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to make a Model static in WPF (MVVM)?

Tags:

c#

static

mvvm

wpf

Let's say some, not all, models in an application are static and are defined as members of a BaseViewModel such that multiple ViewModels (and by extension, Views) can access the exact same data by hitting that which they have inherited. Here is a very basic layout where two derived classes can access the same Model:

public class EmployeeModel
{
    public string Name;
    public int Id;
}

public class BaseViewModel
{
    private static EmployeeModel employeeModel = new Employee Model();
    public EmployeeModel EModel 
    { 
        get { return employeeModel; } 
        set { employeeModel = value; } 
    }

    public BaseViewModel() {}
}

public class EmployeeViewModel : BaseViewModel
{
    public EmployeeViewModel() 
    {
        base.Emodel.Name = "";
    }
}

public class HomeViewModel : BaseViewModel
{
    public EmployeeViewModel()
    {
        base.Emodel.Name = "";
    }
}

In the end, it got the job done as the same data is now showing in multiple views without issue. However, that does not mean there isn't a more appropriate way of which I am unaware. As I am new to WPF, I feel compelled to ask, "is making a model static good practice for the MVVM pattern?" In addition, can this implementation be optimized, and if so, how?

like image 511
Tyler Morrow Avatar asked Jul 03 '13 19:07

Tyler Morrow


1 Answers

This is not a bad practice, would say. So in your case when using model static, makes your program behave as expected, this is a good practice.

Alternative could be to not declare this model static, but declare some static model holder, which returns exactly the same instance on request, so on different view, like now, you will see the same model presented in different way.

hope this helps.

like image 91
Tigran Avatar answered Sep 29 '22 05:09

Tigran