Skip to content

UIFactory

François edited this page Sep 7, 2022 · 4 revisions

Description

A singleton type class is enough to create a View-ViewModel set. In this class, there are two methods:

ControlFactory

public static TControl CreateControl<TControl, TViewModel>(Action<TControl, TViewModel> action, bool initialize = true, params object[] args)
    where TControl: ContentControl
    where TViewModel : ViewModel
{
    return new ControlFactory().CreateControl(action, initialize, args);
}

This factory method create a View-ViewModel set for any type of control deriving from ContentControl.

WindowFactory

public static TWindow CreateWindow<TWindow, TViewModel>(Action<TWindow, TViewModel> action, bool initialize = true, params object[] args)
    where TWindow: Window
    where TViewModel : ViewModel
{
    return new WindowFactory().CreateWindow(action, initialize, args);
}

This factory method create a View-ViewModel set for any type of window (Window).

For these two methods, it is possible to indicate whether you want to execute the Initialize method or not, as well as the parameters to pass to this method if there are any.

Example

Creating a window with its associated ViewModel:

SubWindow subWindow = UIFactory.CreateWindow<SubWindow, SubWindowVM>((win, vm) =>
{
    win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
    win.Title = "Other window";
    vm.PropertyChanged += OnPropertyChanged;
}, true);
subWindow.ShowDialog();

Creating a control with its associated ViewModel:

TextUser textUser = UIFactory.CreateControl<TextUser, TextUserVM>((usr, vm) => 
{                
    vm.ContentText = "Default text...";
}, true);
((MainWindow)Parent).MainDock.Children.Add(textUser);
Clone this wiki locally