Doing my first MVVM WPF application. I expected to see a Main() method in the App.xaml (I'm used to Silverlight) but it isn't there. I added my own Main method. In Silverlight I then created a View linked to a ViewModel and set it as the RootVisual. How do I correctly open my first View Window in WPF?
A:
There are many ways, but I think the WPF equivalent of setting a Silverlight RootVisual is to call Application.Run
App.Run(new MainWindow())
In general, there is no right or wrong way here nor is there an accepted convention. Some people make this call in the Startup event. Other people don't use the event and override OnStartup instead. Still others use StartupUri in App.xaml.
jrwren
2010-08-06 14:01:13
A:
When I created my first (and to date, only) WPF project, to display the appliation's main window (called MainWindow
), I overrode the App
class's OnStartup method as below:
/// <summary>
/// Raises the System.Windows.Application.Startup event.
/// </summary>
/// <param name="e">The <see cref="System.Windows.StartupEventArgs" /> that contains the event data.</param>
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// I did some app-specific stuff here...
MainWindow view = new MainWindow();
// Allow all controls in the window to bind to the ViewModel by setting the
// DataContext, which propagates down the element tree.
MainWindowViewModel viewModel = new MainWindowViewModel();
// and I did some more app-specific stuff here...
view.DataContext = viewModel;
view.Show();
}
I believe this was the recommended way for MVVM applications (was a while back though); this code was taken from a .NET 3.5 application.
robyaw
2010-08-06 14:03:05