WPF TabControl - 如何防止在切换选项卡时卸载?

19
有没有一种方法可以防止WPF选项卡控件切换时选项卡的卸载/重新加载?如果不可能,是否有推荐的缓存选项卡内容的方法,以便在每次选项卡更改时无需重新生成内容?
例如,一个选项卡的UI完全可以自定义并存储在数据库中。当用户选择要处理的对象时,定制布局中的项目将用该对象的数据填充。用户希望初始加载或检索数据时出现轻微延迟,但在切换选项卡时不会出现延迟,而且切换选项卡时延迟非常明显。

我不认为TabItems在选项卡控件中更改所选项目时会被卸载/重新加载。 我不确定,但也许您的TabControl的SelectionChanged逻辑需要更改,以便它不会每次重新查询数据库? - ASanch
2
每次我切换选项卡时(我正在使用MVVM设计模式),DataTemplates的Loaded / Unloaded事件都会运行。 - Rachel
所以,在您的应用程序中,每当选定的选项卡更改时,它都会触发连接到数据库以检索对象数据? - ASanch
1
是的,我想要缓存选项卡,这样它就不必重新构建,或者做一些解决方法来防止每次选项卡更改时卸载/重新加载内容。 - Rachel
3个回答

19
我在这里找到了一个解决方法(网页存档链接,因为网站已经关闭):https://web.archive.org/web/20120429044747/http://eric.burke.name/dotnetmania/2009/04/26/22.09.28 基本上,它会存储选项卡的ContentPresenter,并在切换选项卡时加载它,而不是重新绘制。然而,当拖放选项卡时,仍然会导致延迟,因为那是一个删除/添加操作,但是通过一些修改,我也解决了这个问题(将删除代码以较低的调度优先级运行,然后再运行添加代码,这样添加操作就有机会取消删除操作并使用旧的ContentPresenter,而不是绘制一个新的) 编辑:上面的链接似乎已经失效了,所以我将在这里粘贴代码的副本。代码稍作修改以支持拖放,但应该仍然以相同的方式工作。
using System;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Collections.Specialized;

// Extended TabControl which saves the displayed item so you don't get the performance hit of 
// unloading and reloading the VisualTree when switching tabs

// Obtained from http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
// and made a some modifications so it reuses a TabItem's ContentPresenter when doing drag/drop operations

[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : System.Windows.Controls.TabControl
{
    // Holds all items, but only marks the current tab's item as visible
    private Panel _itemsHolder = null;

    // Temporaily holds deleted item in case this was a drag/drop operation
    private object _deletedObject = null;

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

    /// <summary>
    /// if containers are done, generate the selected item
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    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();
        _itemsHolder = 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 (_itemsHolder == null)
        {
            return;
        }

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

                if (base.Items.Count > 0)
                {
                    base.SelectedItem = base.Items[0];
                    UpdateSelectedItem();
                }

                break;

            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:

                // Search for recently deleted items caused by a Drag/Drop operation
                if (e.NewItems != null && _deletedObject != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        if (_deletedObject == item)
                        {
                            // If the new item is the same as the recently deleted one (i.e. a drag/drop event)
                            // then cancel the deletion and reuse the ContentPresenter so it doesn't have to be 
                            // redrawn. We do need to link the presenter to the new item though (using the Tag)
                            ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                            if (cp != null)
                            {
                                int index = _itemsHolder.Children.IndexOf(cp);

                                (_itemsHolder.Children[index] as ContentPresenter).Tag =
                                    (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
                            }
                            _deletedObject = null;
                        }
                    }
                }

                if (e.OldItems != null)
                {
                    foreach (var item in e.OldItems)
                    {

                        _deletedObject = item;

                        // We want to run this at a slightly later priority in case this
                        // is a drag/drop operation so that we can reuse the template
                        this.Dispatcher.BeginInvoke(DispatcherPriority.DataBind,
                            new Action(delegate()
                        {
                            if (_deletedObject != null)
                            {
                                ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                                if (cp != null)
                                {
                                    this._itemsHolder.Children.Remove(cp);
                                }
                            }
                        }
                        ));
                    }
                }

                UpdateSelectedItem();
                break;

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

    /// <summary>
    /// update the visible child in the ItemsHolder
    /// </summary>
    /// <param name="e"></param>
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        UpdateSelectedItem();
    }

    /// <summary>
    /// generate a ContentPresenter for the selected item
    /// </summary>
    void UpdateSelectedItem()
    {
        if (_itemsHolder == null)
        {
            return;
        }

        // generate a ContentPresenter if necessary
        TabItem item = GetSelectedTabItem();
        if (item != null)
        {
            CreateChildContentPresenter(item);
        }

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

    /// <summary>
    /// create the child ContentPresenter for the given item (could be data or a TabItem)
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    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));
        _itemsHolder.Children.Add(cp);
        return cp;
    }

    /// <summary>
    /// Find the CP for the given object.  data could be a TabItem or a piece of data
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    ContentPresenter FindChildContentPresenter(object data)
    {
        if (data is TabItem)
        {
            data = (data as TabItem).Content;
        }

        if (data == null)
        {
            return null;
        }

        if (_itemsHolder == null)
        {
            return null;
        }

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

        return null;
    }

    /// <summary>
    /// copied from TabControl; wish it were protected in that class instead of private
    /// </summary>
    /// <returns></returns>
    protected TabItem GetSelectedTabItem()
    {
        object selectedItem = base.SelectedItem;
        if (selectedItem == null)
        {
            return null;
        }

        if (_deletedObject == selectedItem)
        { 

        }

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

1
我认为StackOverflow只是错误地解析了链接的markdown。如果您复制/粘贴整个URL(或不使用[] markdown),它就可以工作。 http://web.archive.org/web/20110825185059/http://eric.burke.name/dotnetmania/2009/04/26/22.09.28 - skst
2
我正在尝试使用您的解决方案,因为它似乎可以解决我面临的确切问题。但是,我不知道如何完成这项工作...例如,变量“_itemsHolder”始终为null。控件在我的XAML中,并且一切都正确显示,但是是否有特定的XAML引用需要填补这个空白? - DonBoitnott
@DonBoitnott 在哪个点上它是 null 的?你说它工作正常,所以它必须在某个时候被填充。 - Rachel
2
嗯,“正确”只是指所有内容都正确显示。它在OnApplyTemplate中通过调用GetTemplateChild实例化,此时它为null并且在此之后也是如此。值得一提的是,我是WPF的新手,不知道“PART_ItemsHolder”的作用。 - DonBoitnott
@DonBoitnott 如果它在 OnApplyTemplate 中设置,那么它应该在那里。您确定您正在查看对象模型的相同实例吗?您在什么时候放置断点并看到它为空?如果您遇到问题,最好提出一个新问题,这样我们可以看到相关代码。此外,我认为 "PART_ItemsHolder" 是默认 WPF TabControl 模板的一部分。 - Rachel
2
@Rachel 我问题的答案最终是在这个回答中定义的ControlTemplate - DonBoitnott

2
补充一下,我遇到了类似的问题,并通过在代码后台缓存表示选项卡项内容的用户控件来解决它。
在我的项目中,我有一个选项卡控件,它绑定到一个集合(MVVM)。然而,第一个选项卡是一个概述,它显示所有其他选项卡的摘要视图。我遇到的问题是,每当用户将其选择从项目选项卡移动到概述选项卡时,概述会重新绘制所有摘要数据,这可能需要10-15秒,具体取决于集合中的项目数量。(请注意,没有从数据库或其他任何地方重新加载实际数据,纯粹是摘要视图的绘制需要时间)。
我想要的是,在首次加载数据上下文时仅发生此摘要视图的加载,并且在选项卡之间进行任何后续切换时都是瞬间完成的。
解决方案:
涉及的类: MainWindow.xaml - 包含选项卡控件的主页面。 MainWindow.xaml.cs - 上述代码后台。 MainWindowViewModel.cs - 上述视图模型,包含集合。 Overview.xaml - 绘制概述选项卡项内容的用户控件。 OverviewViewModel.cs - 上述视图模型。
步骤:
1. 在“MainWindow.xaml”中替换绘制概述选项卡项的数据模板为空白用户控件“OverviewPlaceholder”。 2. 在“MainWindowViewModel.cs”中公开对“OverviewViewModel”的引用。 3. 在“MainWindow.xaml.cs”中添加对“Overview”的静态引用。 4. 在用户控件“OverviewPlaceholder”的加载事件中添加一个事件处理程序,在此方法中仅在它为空时实例化对“Overview”的静态引用,将此引用的数据上下文设置为当前数据上下文(即“MainWindowViewModel”)中的“OverviewViewModel”引用,并将占位符的内容设置为对“Overview”的静态引用。
现在,概述页面仅绘制一次,因为每次加载它(即用户单击概述选项卡),它都会将已渲染的静态用户控件放回页面。

-2

我有一个非常简单的解决方案,可以避免在选项卡更改时重新加载选项卡,即在tabItem中使用contentPresenter而不是content属性。

例如(以MVVM风格为例)

替换

      <TabItem Header="Tab1" Content="{Binding Tab1ViewModel}" />

        <TabItem Header="Tab1">
            <ContentPresenter Content="{Binding Tab1ViewModel}" />
        </TabItem>

为什么这个答案被点赞了?ContentPresenter在选项卡切换时将被卸载,包括其内容。这并没有什么作用。 - Sinatr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接