Reputation: 11
I have been dealing with simple MVVM patterns, and have since taken more of a dive into the full capabilities of databinding in WPF. I have an issue that I ran into that I can't seem to wrap my head around. Take the following MainWindowViewModel code for starters:
ObservableCollection<DataRecord> _SomeData = new ObservableCollection<DataRecord>();
public ObservableCollection<DataRecord> SomeData
{
get
{
return _SomeData;
}
set
{
_SomeData = value;
}
}
public MainWindowViewModel()
{
CurrentViewModel.Add(new RandomViewModel(SomeData));
}
Instead of pasting the full lengths of code, I have bound a ListBox to an ObservableCollection<> of ViewModelBase, referencing the Image property of each base added (Image Navigation). Now! For the problem:
I am using a DataTemplate to reference the View from the ViewModel, using the string returned from the ListBox.SelectedItem. Because RandomViewModel requires a parameter passed, whenever I click on the ListBox.SelectedItem, a new View is instantiated instead of the one created in the ListBox. The reason this is happening is simple, the new View requires a RandomViewModel to reference for databinding. So! Using the infamous ListBox.SelectedItem for ViewModel/View Navigation, how am I supposed to create the View, and still reference its ViewModel, even though the ViewModel requires a parameter passed? OR! How am I supposed to use the already instantiated ViewModel and use that as reference to the newly created View?
Upvotes: 0
Views: 504
Reputation: 22445
i dont understand why everybody is doing MVVM with view first. i use view first just for the root/mainwindow and maybe a login dialog. for the rest of the application i dont care about the view/xaml at all and take the Viewmodel first approach. this is so much easier with mvvm. in your case your mainviewmodel handle the list of randomviewmodel like you did. but now instead of creating a random view and assign the randomviewmodel, you just have to bind the seleced randomviewmodel to a contentpresenter. wpf will look at your resources to find a datatemplate to "how should i render this randomviewmodel" and you see you desired view. of yourse every time a new instance of the view is created, but always the same viewmodel is taken.
and thats what mvvm is for me: dont care of your views just handle your viewmodels right.
Upvotes: 1