WPF TabControl only load the selected TabItem

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF TabControl only load the selected TabItem相关的知识,希望对你有一定的参考价值。

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;
        }
    }
}

 

以上是关于WPF TabControl only load the selected TabItem的主要内容,如果未能解决你的问题,请参考以下文章

WPF TabControl Unload俩次的解决方案

WPF 自定义TabControl控件样式

DockPanel 中的 WPF4 TabControl/Grid 隐藏了 StatusBar

WPF SelectedIndex 设置 TabControl 的问题

WPF TabControl 隐藏标头

是否可以在 WPF TabControl 中左对齐标题?