1.binding ItemsSource
public class TabItemViewModel { public string Header { get; set; } public FrameworkElement Content { get; set; } }
xmlns:sc="clr-namespace:System.Collections;assembly=mscorlib"<Window.Resources> <sc:ArrayList x:Key="Datas"> <local:TabItemViewModel Header="uer1"> <local:TabItemViewModel.Content> <local:UserControl1 /> </local:TabItemViewModel.Content> </local:TabItemViewModel> <local:TabItemViewModel Header="uer2"> <local:TabItemViewModel.Content> <local:UserControl2 /> </local:TabItemViewModel.Content> </local:TabItemViewModel> </sc:ArrayList> </Window.Resources> <TabControl ItemsSource="{StaticResource Datas}"> <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="Header" Value="{Binding Header}"/> <Setter Property="Content" Value="{Binding Content}"/> </Style> </TabControl.ItemContainerStyle> </TabControl>
2. use TabItem
<TabControl SelectionChanged="TabControl_SelectionChanged"> <TabItem Header="zzu Red""> <Grid Background="Red"/> </TabItem> <TabItem Header="zzu Orange"> <Grid Background="Orange"/> </TabItem> </TabControl>
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { TabControl tabControl = sender as TabControl; for (int i = 0; i < tabControl.Items.Count; i++) { TabItem item = tabControl.Items[i] as TabItem; if (item.IsSelected) { if (item.Content == null) { item.Content = item.Tag; } else { item.Tag = item.Content; } } else { item.Tag = item.Content; item.Content = null; } } }
时间: 2024-10-20 12:33:45