Robert Strauch
Robert Strauch

Reputation: 12906

Getting a reference to the current instance of the view model

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

Answers (2)

Chen Kinnrot
Chen Kinnrot

Reputation: 21015

You can hold it in some static class and define it as a static resource.

Upvotes: 0

Faster Solutions
Faster Solutions

Reputation: 7003

sure:

var viewModel=DataContext as MainWindowViewModel;

Just cast your DataContext to the type of your viewmodel.

Upvotes: 4

Related Questions