TabItem in a separate XAML

后端 未结 4 1776
萌比男神i
萌比男神i 2020-12-01 06:04

Is it possible to put a TabItem into a separate XAML and reference something like this:


     

         


        
4条回答
  •  星月不相逢
    2020-12-01 06:15

    The previous answer from Tony Borres already covers the most important aspects. But the further comment asks for access from code behind. So I will extend the example from Tony to show this aspect, too. This answer shows the required namespaces. I have added them to the answer from Tony, too.

    To simply make the code more manageable it is recommended to define each tab's data in a user control, but still have the TabItem in the main tab control. This strategy is useful for example to work around FxCop CA1505: "Avoid unmaintainable code" when using a tab control with several tab items.

    Let's assume that this is the original code:

    
        
            
                
                    
                
            
            
                
                    
                
            
        
    
    

    To make the code more manageable the tab contents can be moved into a UserControl such as:

    
        
            
        
    
    

    And then is possible to use the new user control in the TabControl like this:

    
        
            
                
            
            
                
                    
                
            
        
    
    

    Now it possible to access the inner wigdets of the user control from main window and vice versa. Please note the "x:" in front of the user control's name.

    public partial class MainWindow : Window
    {
        private void AccessWidgetWithinUserControl()
        {
            ucTab1Data.txtData1.Text = "New text on Tab 1";
        }
    }
    
    public partial class Tab1Data : UserControl
    {
        private MainWindow mainWindow = null; // Reference to the MainWindow
    
        public Tab1Data()
        {
            InitializeComponent();
        }
    
        // get a reference to main windows when it is available.
        // The Loaded Event is set in the XAML code above.
        private void OnControlLoaded(object sender, RoutedEventArgs e)
        {
            mainWindow = Window.GetWindow(this) as MainWindow;
        }
    
        private void AccessMainWindowsWidget()
        {
            mainWindow.txtData2.Text = "New text on Tab 2 in the main window";
        }
    }
    

    The shown code to access txtData2 would be the same even if is embedded in its own user control.

提交回复
热议问题