Dynamic user control change - WPF

后端 未结 1 343
南方客
南方客 2021-01-06 05:33

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

相关标签:
1条回答
  • 2021-01-06 05:40

    Issues:

    • Firstly don't ever create View related stuff in the ViewModel (UserControl). This is no longer MVVM when you do that.
    • Derive ViewModels from 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's
    • Next you do not need to make everything an ObservableCollection<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.
    • Not sure about this one, maybe you pulled this code snippet as a demo, but do not use margins to separate items in a Grid. Your Layout is essentially just 1 Grid cell and the margins have the items not overlap. If you're not aware of that issue, Check into WPF Layout Articles.
    • Please don't forget principles of OOP, Encapsulation and sorts when writing a UI app. When having Properties like CurrentPageViewModel which you don't intend the View to switch make the property setter private to enforce that.
    • Don't resort to code-behind in the View too soon. Firstly check if it's only a View related concern before doing so. Am talking about your 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];
      }
    }
    
    0 讨论(0)
提交回复
热议问题