Reputation: 2089
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
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:
in the constructor of the view class (MetroWindow constructor, in your case), or
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
Reputation: 2092
This should do it
var datacontext = App.Current.MainWindow.DataContext
Upvotes: 2