Pat
Pat

Reputation: 668

How to load a View model when Window or view is loaded

I created a simple application in C# with a view model and usually you have to declare the view model in he datacontext of the window or usercontrol for it to load. Problem is it loads whenever visual studio has the application opened.

I want it to load when the application is running and window is loaded.

<Window x:Class="GraphApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ViewModel="clr-namespace:GraphApp"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <!-- Insert Model view Here. I want it to load when the window is running, not when I have it opened in visual studio.-->

    </Window.DataContext>

Is this possible?

Upvotes: 0

Views: 4103

Answers (3)

Don Gossett
Don Gossett

Reputation: 781

I know this is old now, but you can to this by first adding a namespace where your view model is located.

xmlns:vm="clr-namespace:MyWpfForm.ViewModel"

Then add this directly under your closing Window Element

<Control.DataContext>
   <vm:MainWindowViewModel />
</Control.DataContext>

where "MainWindowViewModel" is your view model's constructor.

Upvotes: 0

Sheridan
Sheridan

Reputation: 69959

Generally, when we want something to happen after an element has loaded, we handle the FrameworkElement.Loaded event:

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    DataContext = new ViewModel();
}

UPDATE >>>

Another way to achieve this would be to set some DataTemplates and have a property of either the type of your view model, or of a common base view model class:

public BaseViewModel ViewModel { get; set; } // Implement INotifyPropertyChanged here

Then in App.xaml Resources:

<DataTemplate DataType="{x:Type ViewModels:FirstViewModel}">
    <Views:FirstTrackView />
</DataTemplate>
...
<DataTemplate DataType="{x:Type ViewModels:LastViewModel}">
    <Views:LastTrackView />
</DataTemplate>

Then you can implicitly set the DataContext whenever you like in this way and the corresponding view will automatically be displayed:

ViewModel = new SomeViewModel();

Upvotes: 4

Alberto
Alberto

Reputation: 15941

Attach to the Window.Loaded event and:

void OnLoad(object sender, RoutedEventArgs e)
{
    //Check if the event is not raised by the visual studio designer
    if(DesignerProperties.GetIsInDesignMode(this))
      return;

    //Set the data context:
    this.DataContext = //Your viewmodel here
}

Upvotes: 0

Related Questions