IlDrugo
IlDrugo

Reputation: 2089

How to access the DataContext of MainWindow from external classes?

In my MainWindow I've created a DataContext that has a ViewModel and the methods of all controls are added to this. This is the code:

private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
    ViewModelClass viewModel = new ViewModelClass();
    DataContext = viewModel;
}

Now I've different classes (not window only classes) that need access to the control of MainWindow. How can I access MainWindow's DataContext from other classes? Note that I'm using different threads that need to update the UI.

Upvotes: 1

Views: 4577

Answers (2)

Nacharya
Nacharya

Reputation: 229

As adminSoftDK has mentioned, the below code should give you the viewmodel reference, provided the viewmodel is already initialized:

var context = System.Windows.Application.Current.MainWindow.DataContext;

One observation in your code - you are instantiating the viewmodel in the Loaded event. Ideally the viewmodel should be created:

  1. in the constructor of the view class (MetroWindow constructor, in your case), or

  2. in the XAML as

<Window.DataContext> <namespace:ViewModelClass /> </Window.DataContext>

This ensures that the view loads up with an initial state data from the viewmodel.

Upvotes: 0

adminSoftDK
adminSoftDK

Reputation: 2092

This should do it

var datacontext =  App.Current.MainWindow.DataContext

Upvotes: 2

Related Questions