C# 阻止TabControl重新创建其子项

C# 阻止TabControl重新创建其子项,c#,wpf,mvvm,datatemplate,tabcontrol,C#,Wpf,Mvvm,Datatemplate,Tabcontrol,我有一个绑定到TabControl的视图模型的IList。此IList在TabControl的生命周期内不会更改 <TabControl ItemsSource="{Binding Tabs}" SelectedIndex="0" > <TabControl.ItemContainerStyle> <Style TargetType="TabItem"> <Setter Property="Content"

我有一个绑定到
TabControl
的视图模型的
IList
。此
IList
TabControl
的生命周期内不会更改

<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="0" >
    <TabControl.ItemContainerStyle>
        <Style TargetType="TabItem">
            <Setter Property="Content" Value="{Binding}" />
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>
DataTemplate中指定的每个视图都是资源密集型视图,因此我宁愿只创建一次每个视图,但在切换选项卡时,会调用相关视图的构造函数。据我所知,这是
TabControl
的预期行为,但我不清楚调用构造函数的机制是什么


我已经看过了,但是那里提供的解决方案需要我绑定到不需要的视图。

默认情况下,
TabControl
共享一个面板来呈现其内容。要做您想要做的事情(以及许多其他WPF开发人员),您需要像这样扩展
TabControl

TabControlEx.cs

[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : TabControl
{
    private Panel ItemsHolderPanel = null;

    public TabControlEx()
        : base()
    {
        // This is necessary so that we get the initial databound selected item
        ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
    }

    /// <summary>
    /// If containers are done, generate the selected item
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
            UpdateSelectedItem();
        }
    }

    /// <summary>
    /// Get the ItemsHolder and generate any children
    /// </summary>
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        ItemsHolderPanel = GetTemplateChild("PART_ItemsHolder") as Panel;
        UpdateSelectedItem();
    }

    /// <summary>
    /// When the items change we remove any generated panel children and add any new ones as necessary
    /// </summary>
    /// <param name="e"></param>
    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        if (ItemsHolderPanel == null)
            return;

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Reset:
                ItemsHolderPanel.Children.Clear();
                break;

            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:
                if (e.OldItems != null)
                {
                    foreach (var item in e.OldItems)
                    {
                        ContentPresenter cp = FindChildContentPresenter(item);
                        if (cp != null)
                            ItemsHolderPanel.Children.Remove(cp);
                    }
                }

                // Don't do anything with new items because we don't want to
                // create visuals that aren't being shown

                UpdateSelectedItem();
                break;

            case NotifyCollectionChangedAction.Replace:
                throw new NotImplementedException("Replace not implemented yet");
        }
    }

    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        UpdateSelectedItem();
    }

    private void UpdateSelectedItem()
    {
        if (ItemsHolderPanel == null)
            return;

        // Generate a ContentPresenter if necessary
        TabItem item = GetSelectedTabItem();
        if (item != null)
            CreateChildContentPresenter(item);

        // show the right child
        foreach (ContentPresenter child in ItemsHolderPanel.Children)
            child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
    }

    private ContentPresenter CreateChildContentPresenter(object item)
    {
        if (item == null)
            return null;

        ContentPresenter cp = FindChildContentPresenter(item);

        if (cp != null)
            return cp;

        // the actual child to be added.  cp.Tag is a reference to the TabItem
        cp = new ContentPresenter();
        cp.Content = (item is TabItem) ? (item as TabItem).Content : item;
        cp.ContentTemplate = this.SelectedContentTemplate;
        cp.ContentTemplateSelector = this.SelectedContentTemplateSelector;
        cp.ContentStringFormat = this.SelectedContentStringFormat;
        cp.Visibility = Visibility.Collapsed;
        cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
        ItemsHolderPanel.Children.Add(cp);
        return cp;
    }

    private ContentPresenter FindChildContentPresenter(object data)
    {
        if (data is TabItem)
            data = (data as TabItem).Content;

        if (data == null)
            return null;

        if (ItemsHolderPanel == null)
            return null;

        foreach (ContentPresenter cp in ItemsHolderPanel.Children)
        {
            if (cp.Content == data)
                return cp;
        }

        return null;
    }

    protected TabItem GetSelectedTabItem()
    {
        object selectedItem = base.SelectedItem;
        if (selectedItem == null)
            return null;

        TabItem item = selectedItem as TabItem;
        if (item == null)
            item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;

        return item;
    }
}
// Copy C# code from @Dennis's answer, and add the following property after the 
// opening "<Style" tag (this sets the key for the style):
// x:Key="TabControlExStyle"
// Ensure that the namespace for this class is the same as your DataContext.
[TemplatePart(Name=“PART_ItemsHolder”,Type=typeof(Panel))]
公共类TabControlEx:TabControl
{
私有面板ItemsHolderPanel=null;
公共TabControlEx()
:base()
{
//这是必要的,以便我们获得初始数据绑定的选定项
ItemContainerGenerator.StatusChanged+=ItemContainerGenerator\u StatusChanged;
}
/// 
///如果容器已完成,则生成所选项目
/// 
/// 
/// 
私有void ItemContainerGenerator_状态已更改(对象发送者,事件参数e)
{
if(this.ItemContainerGenerator.Status==GeneratorStatus.ContainerGenerated)
{
this.ItemContainerGenerator.StatusChanged-=ItemContainerGenerator\u StatusChanged;
UpdateSelectedItem();
}
}
/// 
///获取ItemsHolder并生成所有子项
/// 
应用程序模板()上的公共重写无效
{
base.OnApplyTemplate();
ItemsHolderPanel=GetTemplateChild(“PART_ItemsHolder”)作为面板;
UpdateSelectedItem();
}
/// 
///当项目更改时,我们将删除所有生成的面板子项,并根据需要添加任何新的子项
/// 
/// 
已更改受保护的覆盖(NotifyCollectionChangedEventArgs e)
{
碱基(e);
如果(ItemsHolderPanel==null)
返回;
开关(电动)
{
案例通知CollectionChangedAction.Reset:
ItemsHolderPanel.Children.Clear();
打破
案例NotifyCollectionChangedAction。添加:
案例NotifyCollectionChangedAction。删除:
如果(例如,OldItems!=null)
{
foreach(e.OldItems中的var项)
{
ContentPresenter cp=FindChildContentPresenter(项目);
如果(cp!=null)
ItemsHolderPanel.Children.Remove(cp);
}
}
//不要对新项目做任何事情,因为我们不想这样做
//创建未显示的视觉效果
UpdateSelectedItem();
打破
案例通知收集更改操作。替换:
抛出新的NotImplementedException(“替换尚未实现”);
}
}
选择更改时受保护的覆盖无效(SelectionChangedEventArgs e)
{
基础。选举变更(e);
UpdateSelectedItem();
}
私有void UpdateSelectedItem()
{
如果(ItemsHolderPanel==null)
返回;
//如有必要,生成ContentPresenter
TabItem item=GetSelectedTabItem();
如果(项!=null)
CreateChildContentPresenter(项目);
//给正确的孩子看
foreach(ItemsHolderPanel.Children中的ContentPresenter子级)
Visibility=((child.tagas TabItem).IsSelected)?Visibility.Visible:Visibility.Collapsed;
}
私有ContentPresenter CreateChildContentPresenter(对象项)
{
如果(项==null)
返回null;
ContentPresenter cp=FindChildContentPresenter(项目);
如果(cp!=null)
返回cp;
//要添加的实际子项.cp.Tag是对TabItem的引用
cp=新的ContentPresenter();
cp.Content=(项目为TabItem)?(项目为TabItem)。内容:项目;
cp.ContentTemplate=此.SelectedContentTemplate;
cp.ContentTemplateSelector=此.SelectedContentTemplateSelector;
cp.ContentStringFormat=此.SelectedContentStringFormat;
cp.可见性=可见性。已折叠;
cp.Tag=(项为TabItem)?项:(this.ItemContainerGenerator.ContainerFromItem(项));
ItemsHolderPanel.Children.Add(cp);
返回cp;
}
私有ContentPresenter FindChildContentPresenter(对象数据)
{
如果(数据为TabItem)
数据=(数据作为TabItem)。内容;
如果(数据==null)
返回null;
如果(ItemsHolderPanel==null)
返回null;
foreach(ItemsHolderPanel.Children中的ContentPresenter cp)
{
if(cp.Content==数据)
返回cp;
}
返回null;
}
受保护的选项卡项GetSelectedTabItem()
{
object selectedItem=base.selectedItem;
如果(selectedItem==null)
返回null;
TabItem item=选择editem作为TabItem;
如果(项==null)
item=base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex)作为TabItem;
退货项目;
}
}
XAML

<Style TargetType="{x:Type controls:TabControlEx}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TabControl}">
                <Grid Background="{TemplateBinding Background}" ClipToBounds="True" KeyboardNavigation.TabNavigation="Local" SnapsToDevicePixels="True">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition x:Name="ColumnDefinition0" />
                        <ColumnDefinition x:Name="ColumnDefinition1" Width="0" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition x:Name="RowDefinition0" Height="Auto" />
                        <RowDefinition x:Name="RowDefinition1" Height="*" />
                    </Grid.RowDefinitions>
                    <DockPanel Margin="2,2,0,0" LastChildFill="False">
                        <TabPanel x:Name="HeaderPanel" Margin="0,0,0,-1" VerticalAlignment="Bottom" Panel.ZIndex="1" DockPanel.Dock="Right"
                                  IsItemsHost="True" KeyboardNavigation.TabIndex="1" />
                    </DockPanel>
                    <Border x:Name="ContentPanel" Grid.Row="1" Grid.Column="0"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            KeyboardNavigation.DirectionalNavigation="Contained" KeyboardNavigation.TabIndex="2" KeyboardNavigation.TabNavigation="Local">
                        <Grid x:Name="PART_ItemsHolder" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
// Copy XAML from @Dennis's answer.

// Copy XAML from @Dennis's answer.
<TabControl
  behaviours:TabControlBehaviour.DoSetSelectedTab="True"
  IsSynchronizedWithCurrentItem="True">
<TabItem Header="Tab 1">
  <TextBox>Hello</TextBox>
</TabItem>
<TabItem Header="Tab 2" >
  <TextBox>Hello 2</TextBox>
</TabItem>
<sdm:TabControlEx
  behaviours:TabControlBehaviour.DoSetSelectedTab="True"
  IsSynchronizedWithCurrentItem="True"
  Style="{StaticResource TabControlExStyle}">
<TabItem Header="Tab 1">
  <TextBox>Hello</TextBox>
</TabItem>
<TabItem Header="Tab 2" >
  <TextBox>Hello 2</TextBox>
</TabItem>
<dx:DXTabControl TabContentCacheMode="CacheAllTabs">
    <dx:DXTabItem Header="Tab 1" >
        <TextBox>Hello</TextBox>
    </dx:DXTabItem>
    <dx:DXTabItem Header="Tab 2">
        <TextBox>Hello 2</TextBox>
    </dx:DXTabItem>
</dx:DXTabControl>
<Window.Resources>
    <converters:ContentGeneratorConverter x:Key="ContentGeneratorConverter"/>

    <DataTemplate x:Key="ItemDataTemplate">
        <StackPanel>
            <TextBox Text="Try to change this text and choose another tab"/>
            <TextBlock Text="{Binding}"/>
        </StackPanel>
    </DataTemplate>

    <markup:Set x:Key="Items">
        <system:String>Red</system:String>
        <system:String>Green</system:String>
        <system:String>Blue</system:String>
    </markup:Set>
</Window.Resources>
public class ContentGeneratorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var control = new ContentControl {ContentTemplate = (DataTemplate) parameter};
        control.SetBinding(ContentControl.ContentProperty, new Binding());
        return control;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
        throw new NotImplementedException();
}
public class Set : List<object> { }
    <TabControl
        ItemsSource="{StaticResource Items}"
        ContentTemplate="{StaticResource ItemDataTemplate}">
    </TabControl>
    <TabControl
        ItemsSource="{StaticResource Items}">
        <TabControl.ItemContainerStyle>
            <Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
                <Setter Property="Content" Value="{Binding Converter={StaticResource ContentGeneratorConverter}, ConverterParameter={StaticResource ItemDataTemplate}}"/>
            </Style>
        </TabControl.ItemContainerStyle>
    </TabControl>