WPF TabControl - 阻止更改选项卡上的卸载?

时间:2010-08-30 14:12:19

标签: wpf caching tabcontrol

当WPF选项卡控件中的选项卡发生变化时,有没有办法阻止Tab Unload / Reload?或者,如果不可能,是否有建议的方法来缓存选项卡内容,以便不必在每次更改选项卡时重新生成它们?

例如,一个选项卡的UI可完全自定义并存储在数据库中。当用户选择要处理的对象时,自定义布局中的项目将填充该对象的数据。用户期望初始加载或检索数据时会有轻微延迟,但在选项卡之间来回切换时则不会,并且更改选项卡时的延迟非常明显。

3 个答案:

答案 0 :(得分:17)

我在这里找到了一个解决方法:https://web.archive.org/web/20120429044747/http://eric.burke.name/dotnetmania/2009/04/26/22.09.28

  

修改:这是更正后的链接:   http://web.archive.org/web/20110825185059/http://eric.burke.name/dotnetmania/2009/04/26/22.09.28

它基本上存储选项卡的ContentPresenter,并在切换选项卡时加载它而不是重绘它。拖动/删除标签时仍然会造成延迟,因为这是一个删除/添加操作,但是经过一些修改后我也可以离开(以较低的调度程序优先级运行删除代码然后添加代码,所以添加操作有机会取消删除操作并使用旧的ContentPresenter而不是绘制新的操作。

修改:上面的链接似乎不再有效,因此我会在此处粘贴代码的副本。它被修改了一下以允许拖放,但它仍然应该以相同的方式工作。

// 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 :(得分:2)

为了补充一点,我遇到了类似的问题并设法通过缓存代表后面代码中标签项内容的用户控件来解决它。

在我的项目中,我有一个绑定到集合(MVVM)的制表符控件。但是,第一个选项卡是概述,显示列表视图中所有其他选项卡的摘要。我遇到的问题是,无论何时用户将其选择从项目选项卡移动到概览选项卡,都会使用所有摘要数据重新绘制概览,这可能需要10-15秒,具体取决于集合中的项目数。 (注意它们不是从数据库或任何东西重新加载实际数据,它纯粹是花费时间的摘要视图的绘图。)

我想要的是,这个加载摘要视图只会在首次加载数据上下文时发生一次,并且任何后续的选项卡之间的切换都是瞬时的。

解决方案:

涉及的课程: MainWindow.xaml - 包含选项卡控件的主页面。 MainWindow.xaml.cs - 上面的代码隐藏。 MainWindowViewModel.cs - 上面视图的View模型,包含集合。 Overview.xaml - 用于绘制概览选项卡项内容的用户控件。 OverviewViewModel.cs - 查看上述视图的模型。

步骤:

  1. 将'MainWindow.xaml'中的datatemplate替换为使用名为'OverviewPlaceholder'的空白用户控件绘制概览标签项

  2. 在'MainWindowViewModel.cs'中公开对'OverviewViewModel'的引用

  3. 在“MainWindow.xaml.cs”中添加对“概述”的静态引用

  4. 将事件处理程序添加到用户控件“OverviewPlaceholder”的已加载事件中,在此方法中,仅当它为null时,将静态引用实例化为“Overview”,将此引用的datacontext设置为“OverviewViewModel”引用在当前的datacontext(即'MainWindowViewModel')中,并将占位符的内容设置为“概述”的静态引用。

  5. 现在概览页面只绘制一次,因为每次加载它(即用户点击概览选项卡)时,它会将已经渲染的静态用户控件放回到页面上。

答案 2 :(得分:-1)

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

,例如(采用MVVM风格)

替换

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

通过

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