Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在选项卡之间切换时,WPF选项卡控件中遇到延迟(每次切换选项卡时都会创建新的视图实例)_Wpf_Mvvm_Tabcontrol - Fatal编程技术网

在选项卡之间切换时,WPF选项卡控件中遇到延迟(每次切换选项卡时都会创建新的视图实例)

在选项卡之间切换时,WPF选项卡控件中遇到延迟(每次切换选项卡时都会创建新的视图实例),wpf,mvvm,tabcontrol,Wpf,Mvvm,Tabcontrol,我是WPF的初学者,在编写代码的过程中,我需要做大量的学习,所以请耐心听我说。我搜索了档案,没有找到任何符合我问题的答案 我目前有一个视图,其中包含一个选项卡控件,该控件最初加载有两个默认选项卡,然后根据用户操作以编程方式添加和删除其他选项卡 我这样做的方式是为不同类型的视图创建一个可视的ViewModels集合,我可以添加和删除这些视图 在视图的Xaml中,我使用了几个不同的数据模板来确定要加载的视图类型 我面临的问题是,当我从一个选项卡点击到另一个选项卡时,我看到了一个接近一秒钟的延迟。我在

我是WPF的初学者,在编写代码的过程中,我需要做大量的学习,所以请耐心听我说。我搜索了档案,没有找到任何符合我问题的答案

我目前有一个视图,其中包含一个选项卡控件,该控件最初加载有两个默认选项卡,然后根据用户操作以编程方式添加和删除其他选项卡

我这样做的方式是为不同类型的视图创建一个可视的ViewModels集合,我可以添加和删除这些视图

在视图的Xaml中,我使用了几个不同的数据模板来确定要加载的视图类型

我面临的问题是,当我从一个选项卡点击到另一个选项卡时,我看到了一个接近一秒钟的延迟。我在视图的代码中添加了一个断点,并注意到每当我单击该选项卡时,都会为视图调用
InitializeComponent()
方法

ViewModels的集合称为
ActiveContents
,它包含
ActiveContent
类型的项。
ActiveContent
类是我创建的,它包含一个名为
ContentItem
的对象,该对象将保存ViewModel

以下是我的项目中的一些代码:

xaml中的一个数据模板:

<UserControl.Resources>
    <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
        .
        .
        .
            </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>

        <DataTemplate DataType="{x:Type viewmodels:InstallQueueViewModel}">
            <local:InstallQueueView DataContext="{Binding Path=DataContext.InstallQueueVM, 
                RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
        </DataTemplate>
    .
    .
    .
        <DataTemplate x:Key="DataTemplateTabControlContent">
            <ContentControl Content="{Binding ContentItem}"></ContentControl>
        </DataTemplate>
</UserControl.Resources>

<Grid>
    <TabControl ItemsSource="{Binding ActiveContents}"
                SelectedIndex="{Binding SelectedTab, Mode=TwoWay}"
                IsSynchronizedWithCurrentItem="True"
                ItemContainerStyle="{DynamicResource TabItemContainerStyleSpacedMedium}"
                ItemTemplate="{StaticResource DataTemplateTabControlHeader}"
                ContentTemplate="{StaticResource DataTemplateTabControlContent}">
    </TabControl>

.
.
.
.
.
.
有没有办法防止它每次都加载视图的新实例?就像我说的,这是我第一次,所以我完全有可能是走错了路——如果我要改变我做某事的方式,请一定要让我知道

我想我应该提到的一件事是,我使用MahApps来获得应用程序的Metro体验。我不确定这是否是造成我所看到的滞后的原因

当我切换到包含
DataGrid
的视图时,我主要看到了延迟。我正在考虑将其更改为
列表视图
,因为数据是只读的,我希望这会给我带来一些改进,但根本原因仍然没有解决


任何帮助都将不胜感激。

这对我来说是一个巨大的问题,我最终创建了一个扩展的
TabControl
,它将在切换选项卡时保存每个
TabItem
ContentPresenter
,并在返回选项卡时重新加载它

代码的原始版本来自,或者您可以在前一段时间有关此问题的相关问题中找到我的代码版本:

//扩展选项卡控件,用于保存显示的项目,这样您就不会获得
//切换选项卡时卸载和重新加载VisualTree
//从http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
//并进行了一些修改,以便在执行拖放操作时重用TabItem的ContentPresenter
[TemplatePart(Name=“PART_ItemsHolder”,Type=typeof(Panel))]
公共类TabControlEx:System.Windows.Controls.TabControl
{
//保存所有项目,但仅将当前选项卡的项目标记为可见
专用面板_itemsHolder=null;
//临时保留已删除的项目,以防这是一个拖放操作
私有对象_deletedObject=null;
公共TabControlEx()
:base()
{
//这是必要的,以便我们获得初始数据绑定的选定项
this.ItemContainerGenerator.StatusChanged+=ItemContainerGenerator\u StatusChanged;
}
/// 
///如果容器已完成,则生成所选项目
/// 
/// 
/// 
void ItemContainerGenerator_状态已更改(对象发送者,事件参数e)
{
if(this.ItemContainerGenerator.Status==GeneratorStatus.ContainerGenerated)
{
this.ItemContainerGenerator.StatusChanged-=ItemContainerGenerator\u StatusChanged;
UpdateSelectedItem();
}
}
/// 
///获取ItemsHolder并生成所有子项
/// 
应用程序模板()上的公共重写无效
{
base.OnApplyTemplate();
_itemsHolder=GetTemplateChild(“PART_itemsHolder”)作为面板;
UpdateSelectedItem();
}
/// 
///当项目更改时,我们将删除所有生成的面板子项,并根据需要添加任何新的子项
/// 
/// 
已更改受保护的覆盖(NotifyCollectionChangedEventArgs e)
{
碱基(e);
如果(_itemsHolder==null)
{
返回;
}
开关(电动)
{
案例通知CollectionChangedAction.Reset:
_itemsHolder.Children.Clear();
如果(base.Items.Count>0)
{
base.SelectedItem=base.Items[0];
UpdateSelectedItem();
}
打破
案例NotifyCollectionChangedAction。添加:
案例NotifyCollectionChangedAction。删除:
//搜索由拖放操作导致的最近删除的项目
if(例如NewItems!=null&&u deletedObject!=null)
{
foreach(e.NewItems中的var项)
{
如果(_deletedObject==项目)
{
//如果新项目与最近删除的项目相同(即拖放事件)
//然后取消删除并重用ContentPresenter,这样就不必删除它
//重新绘制。我们确实需要将演示者链接到新项目(使用标记)
ContentPresenter cp=FindChildContentPresenter(_deletedObject);
如果(cp!=null)
{
// 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;
    }
}