Nick
Nick

Reputation: 3337

WPF MVVM share object between view model and code behind

I am trying to share the following object between my view model and code behind

Dictionary<ItemTypeType, Dictionary<string, Dictionary<int,List<ConfigParameter>>>> ItemToConfigParametersValues

This object is not used in the XAML. It is used in the code behind for several dynamically generated UI Elements.

What is the MVVM Light way of doing this?

Upvotes: 0

Views: 1511

Answers (2)

Fredrik
Fredrik

Reputation: 2317

I would store the viewmodel in a variable so I didnt need to cast DataContext everytime... In the MainWindow.xaml.cs code behind for example:

private MainWindowViewModel _vm;

public MainWindow()
{
    InitializeComponent();

    this._vm = new MainWindowViewModel();
    // this._vm.MyProperty = ... (or does the vm instantiate MyProperty?)
    this.DataContext = this._vm;
}    

private void HandleSomeEvent(object sender, RoutedEventArgs e)
{
    var sharedObject = _vm.MyProperty;
}

Upvotes: 0

Breealzibub
Breealzibub

Reputation: 8095

Well, the ViewModel is typically set as the "DataContext" of the View. Code-behind is part of the View.

So... just expose the data from your ViewModel. In your code-behind, you can access it using the DataContext property (with appropriate casting).

Upvotes: 2

Related Questions