WPF MVVM: Binding a different ViewModel to each TabItem?

前端 未结 5 1146
庸人自扰
庸人自扰 2020-12-28 17:22

I have a main window with a tab control containing 2 tabItems:

\"Main

I currently

5条回答
  •  误落风尘
    2020-12-28 17:56

    You can indeed add the view models for your tabs to a main view model. You can then bind to the child view models in the XAML for your tabs.

    Say that you have three viewmodels: MainViewModel, Tab1ViewModel, and Tab2ViewModel. On your MainViewModel you keep a collection of your tab viewmodels:

    class MainViewModel
    {
        ObservableCollection _children;
    
        public MainViewModel()
        {
            _children = new ObservableCollection();
            _children.Add(new Tab1ViewModel());
            _children.Add(new Tab2ViewModel());
        }
    
        public ObservableCollection Children { get { return _children; } }
    }
    
    
    

    After setting the DataContext of your main window to your MainViewModel you can bind the DataContext of your tabs by referencing the Children property:

    
        
          
        
        
          
        
    
    

    提交回复
    热议问题