Reputation: 12906
Let's say I have a WPF application which makes use of the MVVM pattern. The application's main window defines its data context in the XAML:
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
Is it possible to get a reference to the current instance of MainWindowViewModel
in the XAML code-behind after InitializeComponent()
? I know this is not recommended when using MVVM but I can't figure out any other way for solving my problem.
Upvotes: 1
Views: 3407
Reputation: 21015
You can hold it in some static class and define it as a static resource.
Upvotes: 0
Reputation: 7003
sure:
var viewModel=DataContext as MainWindowViewModel;
Just cast your DataContext to the type of your viewmodel.
Upvotes: 4