4

ContentControl で一度に 1 つのビューを表示するアプリケーションがあります。私は現在の解決策を持っていますが、メモリ管理のためのより良い解決策があるかどうか興味がありました.

私の現在の設計では、表示する必要があるときに新しいオブジェクトを作成し、表示されなくなったときにそれらを破棄します。これがより良いアプローチなのか、それとも各ビューへの参照を維持し、それらの参照間で交換する方が良いのか、私は興味がありますか?

ここで、私のアプリケーション レイアウトについてもう少し説明します。

私の 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>

繰り返しになりますが、私がよく知らないバックグラウンドでどのようなメモリ管理が行われているのか興味があります。何かを折りたたむと、完全に冬眠状態になりますか? 私はいくつかのもの(ヒットテスト、イベント、キー入力、フォーカスなどはありません)を読みましたが、アニメーションやその他のものはどうですか?

ご意見ありがとうございます。

4

3 に答える 3

3

ビューの作成にかなりの費用がかかるような状況に遭遇したことがあるので、ユーザーが切り替えるたびにビューを再作成する必要がないように、それらをメモリに保存したいと考えました。

私の最終的な解決策は、同じ動作を達成するために使用する拡張を再利用するTabControlことでした (タブを切り替えるときに WPF が TabItems を破棄するのを停止します) ContentPresenter

変更する必要があったのは、上書きする必要があったため、表示されるのは TabControlTabControl.Templateの実際の部分だけでした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>
于 2012-10-10T17:06:36.250 に答える
1

現在のアプローチを継続することもできます。提供された :

  • ViewModel オブジェクトは、構築が簡単/軽量です。これは、オブジェクトの内部詳細を外部から注入する場合に可能です (依存性注入の原則に従います)。
  • 内部の詳細をバッファリング/保存してから、ビューモデルオブジェクトを構築するときに注入することができます。
  • ビューモデルに IDisposable を実装して、破棄中に内部の詳細を確実にクリアします。

ビューモデルをメモリにキャッシュしておくことの欠点の 1 つは、そのバインドです。ビューが範囲外になったときに、ビューとビューモデルの間で流れるバインド通知を停止する必要がある場合は、ビューモデルを null に設定します。ビューモデルの構築が軽量である場合、ビューモデルをすばやく構築し、ビュー データ コンテキストに割り当てることができます。

その後、アプローチ 2 に示すようにビューをキャッシュできます。ビューモデルが適切なデータでプラグインされている場合、ビューを繰り返し構築する意味はないと思います。viewmodel を null に設定すると、datacontext ビューのバインディングにより、すべてのバインディングがクリーンアップされます。後で新しいビューモデルをデータコンテキストとして設定すると、ビューは新しいデータでロードされます。

注: ビューモデルがメモリ リークなしで適切に破棄されることを確認してください。SOS.DLLを使用して、ビジュアル スタジオのデバッグを通じてビューモデルのインスタンス数をチェックします。

于 2012-10-10T16:17:13.900 に答える
1

考慮すべきもう 1 つのオプション: これは、IoC コンテナーや依存性注入フレームワークなどを使用するためのシナリオですか? 多くの場合、DI フレームワークは、オブジェクトのコンテナー管理の有効期間をサポートしています。Unity Application Block または MEF が気になる場合は、こちらを参照することをお勧めします。

于 2012-10-10T17:18:21.687 に答える