gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:48:46 30 4
gpt4 key购买 nike

我是 WPF 的初学者,在编码时我必须做很多学习,所以请耐心等待。我搜索了文件,但找不到任何适合我的问题的答案。

我当前有一个包含选项卡控件的 View ,该控件最初加载了 2 个默认选项卡,然后根据用户操作以编程方式添加和删除其他选项卡。

我这样做的方法是为不同类型的 View 创建一个可观察的 ViewModel 集合,我可以添加和删除这些 View 。

在 View 的 Xaml 中,我有一些不同的 DataTemplates,用于确定要加载哪种类型的 View 。

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

ViewModel 的集合称为 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>

有没有办法阻止它每次加载 View 的新实例?就像我说的,这是我第一次,所以完全有可能我只是以错误的方式来做这件事 - 如果我应该改变我做某事的方式,请告诉我。

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

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

任何帮助将不胜感激。

最佳答案

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

原版代码来自here ,或者您可以在不久前关于该问题的相关问题中找到我的代码版本:WPF TabControl - Preventing Unload on Tab Change?

// 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;
}
}

关于wpf - 在选项卡之间切换时,WPF 选项卡控件中遇到延迟(每次切换选项卡时都会创建新的 View 实例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23252643/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com