c# - 在单个 ContentControl 中管理多个 View / View 模型

标签 c# wpf mvvm wpf-controls mvvm-light

我有一个应用程序,它在 ContentControl 中一次显示一个 View 。我有一个当前的解决方案,但很好奇是否有更好的内存管理解决方案。

我当前的设计在需要显示时创建新对象,在它们不再可见时销毁它们。我很好奇这是更好的方法,还是维护对每个 View 的引用并在这些引用之间交换更好?

这里是我的应用程序布局的更多解释:

我的 MainWindow.xaml 的一个非常简化的版本如下所示:

<Window ... >
  <Window.Resources>
    <DataTemplate DataType="{x:Type vm:SplashViewModel}">
        <view:SplashView />
    </DataTemplate>
    <DataTemplate DataType="{x:Type vm:MediaPlayerViewModel}">
        <view:MediaPlayerView />
    </DataTemplate>
  </Window.Resources>
  <Grid>
    <ContentControl Content="{Binding ActiveModule}" />
  </Grid>
</Window>

在我的 MainViewModel.cs 中,我将 ActiveModule 参数与新初始化的 ViewModel 交换。例如,我对交换内容的伪代码逻辑检查类似于:

if (logicCheck == "SlideShow")
  ActiveModule = new SlideShowViewModel();
else if (logicCheck == "MediaPlayer")
  ActiveModule = new MediaPlayerViewModel();
else
  ActiveModule = new SplashScreenViewModel();

但是,仅仅维护一个引用在速度和内存使用方面会更合适吗?

替代选项 1:创建对每个 ViewModel 的静态引用并在它们之间交换...

private static ViewModelBase _slideShow = new SlideShowViewModel();
private static ViewModelBase _mediaPlayer = new MediaPlayerViewModel();
private static ViewModelBase _splashView = new SplashScreenViewModel();

private void SwitchModule(string logicCheck) {
  if (logicCheck == "SlideShow")
    ActiveModule = _slideShow;
  else if (logicCheck == "MediaPlayer")
    ActiveModule = _mediaPlayer;
  else
    ActiveModule = _splashView;
}

我不会在这里不断地创建/销毁,但在我看来,这种方法会浪费内存,因为未使用的模块只是闲置。或者... WPF 是否在幕后做了一些特殊的事情来避免这种情况?

替代选项 2:将每个可用模块放在 XAML 中并在那里显示/隐藏它们:

<Window ... >
  <Grid>
    <view:SplashScreenView Visibility="Visible" />
    <view:MediaPlayerView Visibility="Collapsed" />
    <view:SlideShowView Visibility="Collapsed" />
  </Grid>
</Window>

同样,我很好奇在我不熟悉的后台可能发生了什么内存管理。当我折叠某样东西时,它会完全进入某种休眠状态吗?我读到有些东西确实如此(没有 HitTest 、事件、关键输入、焦点......)但是动画和其他东西呢?

感谢任何输入!

最佳答案

我曾经遇到过这种情况,我的 View 创建起来非常昂贵,所以我想将它们存储在内存中,以避免在用户来回切换时不得不重新创建它们。

我的最终解决方案是重用一个扩展的 TabControl,我用它来完成相同的行为(在切换选项卡时阻止 WPF 破坏 TabItems),它存储 ContentPresenter您切换标签页,并在可能的情况下在切换回来时重新加载它。

我唯一需要更改的是我必须覆盖 TabControl.Template 因此唯一显示的是 TabControl 的实际 SelectedItem 部分

我的 XAML 最终看起来像这样:

<local:TabControlEx ItemsSource="{Binding AvailableModules}"
                    SelectedItem="{Binding ActiveModule}"
                    Template="{StaticResource BlankTabControlTemplate}" />

扩展的 TabControl 的实际代码如下所示:

// 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://www.pluralsight-training.net/community/blogs/eburke/archive/2009/04/30/keeping-the-wpf-tab-control-from-destroying-its-children.aspx
// 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;
    }
}

我也不是很肯定,但我认为我的空白 TabControl 模板看起来像这样:

<Style x:Key="BlankTabControlTemplate" TargetType="{x:Type local:TabControlEx}">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:TabControlEx}">
                <DockPanel>
                    <!-- This is needed to draw TabControls with Bound items -->
                    <StackPanel IsItemsHost="True" Height="0" Width="0" />
                    <Grid x:Name="PART_ItemsHolder" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

关于c# - 在单个 ContentControl 中管理多个 View / View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12823197/

相关文章:

c# - 为什么我的 C# Xml 代码仅在枚举变量 enumerable 时才起作用

c# - 如何在 Windows Phone 8.1 中阻止一个特定的键

c# - 如何删除数组中的重复值?

c# - 在 Asp.net Mvc 5 应用程序中将用户分配给项目列表

wpf - Silverlight/WPF 和 Blend : DataBind a text field, 但定义设计时值?

collections - 在Silverlight 2中渲染 View 模型的异构集合

c# - 来自主窗口文本框的用户控件文本框内的 wpf 绑定(bind)文本

c# - Entity Framework - 绑定(bind) WPF TreeView 控件

c# - 使用自定义 ItemsPanel 模板的 WPF ListBox 如何根据其项目的大小调整自身大小

c# - 使用 WPF 和 MVVM 设置数据绑定(bind)的问题