【问题标题】:Managing Multiple Views/ViewModels In A Single ContentControl在单个 ContentControl 中管理多个视图/视图模型
【发布时间】:2012-10-10 15:38:39
【问题描述】:

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

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

下面是对我的应用程序布局的更多解释:

我的 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();

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

Alt 选项 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 在幕后有什么特别的事情可以避免这种情况吗?

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

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

再次,我很好奇在我不熟悉的背景中可能发生的内存管理。当我折叠某物时,它会完全进入某种休眠状态吗?我读过有些东西可以(没有命中测试、事件、关键输入、焦点……)但是动画和其他东西呢?

感谢您的任何意见!

【问题讨论】:

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


    【解决方案1】:

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

    我的最终解决方案是重用一个扩展的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>
    

    【讨论】:

      【解决方案2】:

      您可以选择继续当前的方法;提供:

      • ViewModel 对象易于构建/重量轻。如果您从外部注入对象的内部细节(遵循依赖注入原则),这是可能的。
      • 您可以缓冲/存储内部细节,然后在构造视图模型对象时注入。
      • 在您的视图模型上实施 IDisposable 以确保您在处置期间清除内部细节。

      将视图模型缓存在内存中的缺点之一是它们的绑定。如果在视图超出范围时必须停止绑定通知以在视图和视图模型之间流动,则将视图模型设置为 null。如果视图模型构建是轻量级的,您可以快速构建视图模型并分配回视图数据上下文。

      然后您可以缓存视图,如方法 2 所示。我相信如果视图模型插入了正确的数据,重复构建视图是没有意义的。当您将 viewmodel 设置为 null 时,由于绑定 datacontext 视图将清除所有绑定。稍后将新视图模型设置为数据上下文,视图将加载新数据。

      注意:确保视图模型得到正确处理,没有内存泄漏。使用SOS.DLL通过Visual Studio 调试持续检查viewmodel 实例数。

      【讨论】:

        【解决方案3】:

        另一个需要考虑的选项:这是使用 IoC 容器和依赖注入框架之类的场景吗?通常,DI 框架支持对象的容器管理生命周期。如果你喜欢,我建议查看 Unity Application Block 或 MEF。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-02-19
          • 2013-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-13
          相关资源
          最近更新 更多