I\'m developing an app in WPF and I need to change in runtime a content of a ContentControl
depending than the user selected on ComboBox
.
I
Issues:
UserControl
). This is no longer MVVM when you do that.ViewModelBase
and not ObservableObject
unless you have a compelling reason to not use ViewModelBase
when using MVVMLight. Keep ObservableObject
inheritence for Models. Serves as a nice separation between VM's and M'sObservableCollection<T>
like your _pagesViewModel
. You do not have that bound to anything in your View's so it's just a waste. Just keep that as a private List or array. Check what a type actually does in difference to a similar other one.CurrentPageViewModel
which you don't intend the View to switch make the property setter private
to enforce that.ComboBox
SelectionChanged
event handler. Your purpose of that in this demo is to switch the Bound ViewModel which is held in the VM. Hence it's not something that the View is solely responsible for. Thus look for a VM involved approach.Solution:
You can get a working example of your code with the fixes for above from Here and try it out yourself.
Points 1 -> 5 are just basic straightforward changes.
For 6, I've created a SelectedVMIndex
property in the MainViewModel which is bound to the SelectedIndex
of the ComboBox
. Thus when the selected index flips, the property setter after updating itself updates the CurrentPageViewModel
as well such as
public int SelectedVMIndex {
get {
return _selectedVMIndex;
}
set {
if (_selectedVMIndex == value) {
return;
}
_selectedVMIndex = value;
RaisePropertyChanged(() => SelectedVMIndex);
CurrentPageViewModel = _pagesViewModel[_selectedVMIndex];
}
}