In the case of MVVM, you would expect ViewModel to have only one instance of the entire application. The traditional practice is to use singleton mode to implement:
public class Viewmodeltest
{
Private Viewmodeltest ()
{
}
private static Viewmodeltest Viewmodelinstace;
public static Viewmodeltest Getviewmodeltestinstace ()
{
if (Viewmodelinstace = = null)
{
Viewmodelinstace = new Viewmodeltest ();
}
return viewmodelinstace;
}
}
It's a traditional singleton pattern, but we're going to have a lot of viewmodel at the time of development. If every viewmodel is going to implement a single-instance mode, the workload is a huge project. So here is the use of reflection to provide a simple and common way to implement the code as follows:
A: First Onstartup event in App.xaml.cs declares a global dictionary collection for storing our ViewModel
protected override void Onstartup (StartupEventArgs e)
{
Base. Onstartup (e);
Creating a ViewModel Global map
application.current.properties["Viewmodelmap"] = new dictionary<string, object> ();
}
Second: Using reflection to dynamically create ViewModel
Public classViewmodelfactory { Public Static ObjectGetviewmodel (Type vm_type) {Dictionary<string,Object> dic = application.current.properties["Viewmodelmap"] asdictionary<string,Object>; if(DIC. ContainsKey (Vm_type. FullName)) {returnDic[vm_type. FullName]; } Else {ObjectNEW_VM =Activator.CreateInstance (Vm_type); Dic. ADD (Vm_type. FullName, NEW_VM); returnNEW_VM; } }
Three: Call the Getviewmodel method directly when assigning DataContext to a view
Public class viewmodeltest { private viewmodeltest () { } }
Public Partial class viewmodeltestwindow:window{ public Window () { this. InitializeComponent (); this. DataContext = Viewmodelfactory.getviewmodel (typeof(viewmodeltest)); }}
Using reflection to dynamically create ViewModel to implement a single example under MVVM