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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With