首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在WPF中预渲染TabItem上的控件?

如何在WPF中预渲染TabItem上的控件?
EN

Stack Overflow用户
提问于 2010-02-03 23:44:58
回答 4查看 4.1K关注 0票数 7

C# XBap应用程序

我有一个里面有四个TabItems的TabControl。其中两个TabItems只包含一个来自WPFToolkit的DataGrid,它从SQL Server数据库中拉出一个相当小的数据表(100行乘4列)。我的问题是,当我加载我的应用程序时,我点击了一个包含数据网格的TabItems。在我看来,有2-3秒的停顿,然后才把标签带到焦点上。只有在第一次单击选项卡时才会发生这种情况。它似乎是数据网格的渲染。

如何在应用程序加载时使这些标签预渲染,以便当用户单击标签时,在标签显示前不会有2-3秒的初始暂停。

谢谢

EN

回答 4

Stack Overflow用户

发布于 2012-04-18 21:54:46

我们使用标准的WPF TabControl,问题是每当您更改SelectedItem时,它都会丢弃VisualTree。

我们最终做的是创建一个特殊的TabControl (我称之为TabControlEx),它保持所有项目的呈现,但选择简单地显示/隐藏TabItems的ContentPresenters。

下面是相关的代码

代码语言:javascript
运行
复制
using System;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace MVVM.Demo
{
    /// <summary>
    /// The standard WPF TabControl is quite bad in the fact that it only
    /// even contains the current TabItem in the VisualTree, so if you
    /// have complex views it takes a while to re-create the view each tab
    /// selection change.Which makes the standard TabControl very sticky to
    /// work with. This class along with its associated ControlTemplate
    /// allow all TabItems to remain in the VisualTree without it being Sticky.
    /// It does this by keeping all TabItem content in the VisualTree but
    /// hides all inactive TabItem content, and only keeps the active TabItem
    /// content shown.
    /// </summary>
    [TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
    public class TabControlEx : TabControl
    {
        #region Data
        private Panel itemsHolder = null;
        #endregion

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

        #region Public/Protected Methods
        /// <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();
                    break;

                case NotifyCollectionChangedAction.Add:
                case NotifyCollectionChangedAction.Remove:
                    if (e.OldItems != null)
                    {
                        foreach (var item in e.OldItems)
                        {
                            ContentPresenter cp = FindChildContentPresenter(item);
                            if (cp != null)
                            {
                                itemsHolder.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");
            }
        }

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

        /// <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;
            }
            TabItem item = selectedItem as TabItem;
            if (item == null)
            {
                item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;
            }
            return item;
        }
        #endregion

        #region Private Methods

        /// <summary>
        /// in some scenarios we need to update when loaded in case the 
        /// ApplyTemplate happens before the databind.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControlEx_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateSelectedItem();
        }

        /// <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>
        /// generate a ContentPresenter for the selected item
        /// </summary>
        private 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>
        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));
            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>
        private 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;
        }
        #endregion
    }
}

你可以像这样将它作为模板(你可能需要为Left/Right TabStripLocation扩展它)

代码语言:javascript
运行
复制
<ControlTemplate x:Key="MainTabControlTemplateEx"
                TargetType="{x:Type controls:TabControlEx}">
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition x:Name="row0" Height="Auto"/>
            <RowDefinition x:Name="row1" Height="4"/>
            <RowDefinition x:Name="row2" Height="*"/>
        </Grid.RowDefinitions>

        <TabPanel x:Name="tabpanel" 
            Background="{StaticResource OutlookButtonHighlight}"
            Margin="0"
            Grid.Row="0"
            IsItemsHost="True" />

        <Grid x:Name="divider"
                Grid.Row="1" Background="Black" 
                HorizontalAlignment="Stretch"/>

        <Grid x:Name="PART_ItemsHolder"
                Grid.Row="2"/>
    </Grid>
    <!-- no content presenter -->
    <ControlTemplate.Triggers>
        <Trigger Property="TabStripPlacement" Value="Top">
            <Setter TargetName="tabpanel" Property="Grid.Row" Value="0"/>
            <Setter TargetName="divider" Property="Grid.Row" Value="1"/>
            <Setter TargetName="PART_ItemsHolder" Property="Grid.Row" Value="2" />
            <Setter TargetName="row0" Property="Height" Value="Auto" />
            <Setter TargetName="row1" Property="Height" Value="4" />
            <Setter TargetName="row2" Property="Height" Value="*" />
        </Trigger>
        <Trigger Property="TabStripPlacement" Value="Bottom">
            <Setter TargetName="tabpanel" Property="Grid.Row" Value="2" />
            <Setter TargetName="divider" Property="Grid.Row" Value="1" />
            <Setter TargetName="PART_ItemsHolder" Property="Grid.Row" Value="0" />
            <Setter TargetName="row0" Property="Height" Value="*" />
            <Setter TargetName="row1" Property="Height" Value="4" />
            <Setter TargetName="row2" Property="Height" Value="Auto" />
        </Trigger>
    </ControlTemplate.Triggers>

</ControlTemplate>

你可以像这样使用它

代码语言:javascript
运行
复制
<local:TabControlEx 
        IsSynchronizedWithCurrentItem="True" 
        ItemsSource="{Binding Path=Workspaces}" 
        Template="{StaticResource MainTabControlTemplateEx}">
</local:TabControlEx>

它工作得很好,我们已经用了很长一段时间了。

票数 7
EN

Stack Overflow用户

发布于 2011-07-25 23:40:18

问题不在于获取数据(您可以在单独的线程中预加载数据),而在于在数据网格中构建可视项。

如果你查看Snoop,你可以看到有很多可视化的项目,如果你不需要所有的数据网格功能,你可以使用更简单的表示(ListView/ItemsControl/Custom)

票数 0
EN

Stack Overflow用户

发布于 2012-06-03 22:39:59

在选择时动态加载选项卡内容,为了使UI具有响应性,请使用类似于下面的代码:

代码语言:javascript
运行
复制
 private void tab_Selected(object sender, EventArgs e)
{
   //Get the selected tab
 Action loadTab = delegate
{
  LoadSelectedTab(tabItem);
}
Dispatcher.BeginInvoke(DispatcherPriority.Background, loadTab);
}
public void LoadSelectedTab(TabItem item)
{
  item.Content = new EmployeeTab();
  .....
}

UI响应器将非常快,UI开始加载非常快,您不会看到任何延迟的暂停

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2193166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档