Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory for a View in MVVM

Tags:

c#

mvvm

wpf

factory

There is an user control for ContextMenu which will be re-used in other user controls. The problem is the controls which would like to use this Contextmenu needs to create the ContextMenuViewModel and populate its DataContext which is the normal practice.

Is there a way to create a factory for the View so it will be created on the fly and not worried about its data context from the control which is consuming it?

like image 290
Carbine Avatar asked Jan 20 '26 21:01

Carbine


1 Answers

You can use Locator pattern

Ex:

uses of a “Locator” such as:

DataContext="{Binding Main, Source={StaticResource Locator}}">

There is locators created in the application.

<Application x:Class="XXX.App"
             xmlns:views="clr-namespace:XXX.Views"
             xmlns:vm="clr-namespace:XXX.ViewModels"
             StartupUri="MainWindow.xaml"
             >
    <Application.Resources>
...
        <vm:ViewModelLocator x:Key="Locator"  />   
...     
    </Application.Resources>
</Application>

The class "Locator":

public class ViewModelLocator
{            
   private static MainViewModel _main;    

   /// Initializes a new instance of the ViewModelLocator class.

   public ViewModelLocator()            
   {                
      _main = new MainViewModel();            
   }    

  /// Gets the Main property which defines the main viewmodel.            

  public MainViewModel Main
  {                
     get                
       {              
       return _main;                
       }            
  }        


}
like image 173
Zhenia Avatar answered Jan 22 '26 12:01

Zhenia