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:
- Override the
OnStartupmethod in theAppclass, where you will create a window instance and set theDataContextthere.
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.
- Create the
MainWindowViewModelinstance 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
ViewModelattribute in theMainViewModel?
Yes.
