WPF tab control and MVVM selection

前端 未结 4 1374
遥遥无期
遥遥无期 2020-12-29 04:44

I have a TabControl in an MVVM WPF application. It is defined as follows.



        
4条回答
  •  自闭症患者
    2020-12-29 05:20

    The below code sample will create a dynamic tab using MVVM.

    XAML

    
    
        
            
                
            
        
    
        
            
                
            
        
    
    

    Modal Class

    TabCategoryItem represents each tab item. On two properties, TabHeader will display a tab caption and TabContent contains the content/control to fill in each tab.

    Public Class TabCategoryItem
    
        Public Property TabHeader As String
        Public Property TabContent As UIElement
    End Class
    

    VM Class

    Public Class vmClass
    
        Public Property tabCategory As ObjectModel.ObservableCollection(Of TabCategoryItem)
        Public Property SelectedCategory As TabCategoryItem
    End Class
    

    The below code will fill and bind the content. I am creating two tabs, tab1 and tab2. Both tabs will contain text boxes. You can use any UIelement instead of text boxes.

    Dim vm As New vmClass
    
    vm.tabCategory = New ObjectModel.ObservableCollection(Of TabCategoryItem)
    
    'VM.tabCategory colection will create all tabs
    
    vm.tabCategory.Add(New TabCategoryItem() With {.TabHeader = "Tab1", .TabContent = new TextBlock().Text = "My first Tab control1"})
    vm.tabCategory.Add(New TabCategoryItem() With {.TabHeader = "Tab2", .TabContent = new TextBlock().Text = "My first Tab control2"})
    
    mywindow.DataContent = vm
    

提交回复
热议问题