Home > OS >  How to implement a MainViewModel in a WPF App?
How to implement a MainViewModel in a WPF App?

Time:06-12

I need help understanding the implementation of a MainViewModel in a WPF App.

For instance, let's say I have a Window named Tools which is made of several ViewModels. How can I set the DataContext of that Window to a MainViewModel which represents all my ViewModels? Is the DataContext of one element, let's say a ListBox, going to be bound to its corresponding ViewModel attribute in the MainViewModel ?

CodePudding user response:

You have several options here:

  1. Override the OnStartup method in the App class, where you will create a window instance and set the DataContext there.
protected override OnStartup(/*Some args here*/)
{
    base.OnStartUp(/*Some args here*/);

    var mainWindowViewModel = new MainWindowViewModel();
    var mainWindow = new MainWindow
    {
        DataContext = mainWindowViewModel
    };

    MainWindow = mainWindow;
    MainWindow.Show();
}

Don't forget to remove the StartupUri attribute in the App.xaml file and set the ShutdownMode=OnMainWindowClose there.

  1. Create the MainWindowViewModel instance in the window constructor.
public class MainWindow : Window
{
    public MainWindow()
    {
        DataContext = new MainWindowViewModel()
    }
}

To sum up - the first approach is better in my opinion because You can resolve all view-model dependencies within the App class and separate that logic from the view-model itself.

Is the DataContext of one element, let's say a ListBox, going to be bound to its corresponding ViewModel attribute in the MainViewModel?

Yes.

  • Related