2012-07-17 38 views
1

我必須在WPF中的兩個視圖之間切換。我有一個DataTemplate使用ViewModels來根據ViewModel推斷繪製哪個視圖。總之:如何處理由DataTemplate創建的usercontrols

<DataTemplate DataType="{x:Type ..:RedScreenViewModel}"> 
<...:RedScreenViewModel/> 
</DataTemplate> 

一時心血來潮,我決定視圖之間快速切換..和WPF應用程序的內存使用量猛增至2GB。現在你可能會爭辯說,在現實生活中,沒有人會做我做過的事情。但我想知道如何釋放分配的內存。卸載是絕對要求的,我已退訂任何事件處理程序。 但它沒有幫助。 DevExpress或WPF是否擁有可以告訴.NET處置用戶控件的屬性? 那些我發現的DevExpress但做小人物是:

DisposeOnWindowClosing 
DestroyOnClosingChildren 

創建視圖是非常複雜的,我已經在努力節省內存改組佈局。但同樣增加。 建議將非常感謝。

編輯: 析構函數不稱爲但是...

+0

WPF組件沒有Dispose()方法,因爲它們依賴於垃圾回收器。如果切換視圖導致那麼多「浪費數據」,那麼嘗試調用'GC.Collect()'。此外,確保不存在對舊數據的引用。 – 2012-07-17 21:41:42

+2

沒有看到你的視圖/視圖模型的實現,很難說出爲什麼這麼多的內存在附近。我建議使用內存分析器來確定哪些對象是根源的。 .NET Memory Profiler是相當史詩般的(http://memprofiler.com/),它們有一個免費的線索。 – 2012-07-18 00:29:50

+0

@RafaelGoodman我發現了這個問題,但無法解決它:( 我正在使用的第三方庫,它的ItemsSource綁定到一個ObservableCollection。它在後臺訂閱了該集合的INotifiedPropertyChanged。該訂閱意味着Dispose永遠不會我試過的一種方法是將Collection綁定到null,這樣可以解決問題,但是我討厭這個解決方案,因爲它不能正常工作。 – 2012-07-18 09:06:06

回答

0

這是你如何處置嵌套一個ItemsControl內部的用戶控件(在這種情況下:一個列表框)

 public void Dispose() 
     { 
      if (this.listb != null) 
      { 
       for (int count = 0; count < this.listb.Items.Count; count++) 
       { 
        DependencyObject container = this.listb.ItemContainerGenerator.ContainerFromIndex(count); 
        UserControl userControl = container.GetVisualDescendent<UserControl>(); 
        IDisposable controlToPotentiallyDispose = userControl as IDisposable; 
        if (controlToPotentiallyDispose != null) 
         controlToPotentiallyDispose.Dispose(); 
        controlToPotentiallyDispose = null; 
       } 
      } 
      if (this.ViewModel != null) 
      { 
       this.ViewModel.Dispose(); 
       this.ViewModel = null; 
      } 
      this.listb = null; 
     } 

注意數組listB是要從中查找項目的列表框的名稱。
此外,這個Dispose()方法應該在xaml.cs中,並且應該在您不再需要視圖時調用它。

HTH,

巴布。