【问题标题】:WPF Combobox "leaks" memoryWPF 组合框“泄漏”内存
【发布时间】:2013-08-07 06:23:14
【问题描述】:

我遇到了 WPF 中组合框的问题,它们似乎挂在打开的第一个 DataContext 上。当我更改 ComboBox 上的 DataContext 时,子 PopupRoot 对象仍然引用旧的 DataContext。

起初我认为我们做错了什么,但我无法弄清楚可能是什么,所以我试图简化。我已经设法以一种非常简单的形式重新创建了我在应用程序中看到的行为,因此它看起来更像是 WPF ComboBox 实现中的一个错误。这听起来有点争议,所以我想我应该求助于 stackoverflow。

示例的核心代码如下:

<Window x:Class="ComboBoxTest.MainWindow" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="150" Width="525">
    <DockPanel>
        <Button Click="ReloadModel" Width="137" Height="40">Reload Model</Button>
        <ComboBox Name="ComboBox" 
            ItemsSource="{Binding AvailableOptions}" 
            SelectedItem="{Binding SelectedOption}" 
            Width="235" Height="43">
        </ComboBox>
    </DockPanel>
</Window>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        var newModel = new ViewModel();
        ComboBox.DataContext = newModel;
    }

    private void ReloadModel(object sender, RoutedEventArgs e)
    {        
        var newModel = new ViewModel();
        ComboBox.DataContext = newModel;
    }
}

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
        : this(new[] { "Option 1", "Option 2", "Option 3" })
    { }

    public ViewModel(IEnumerable<string> options)
    {
        _selectedOption = options.First();
        _availableOptions = new ObservableCollection<string>(options);
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        var propertyChangedHandler = PropertyChanged;
        if (propertyChangedHandler != null)
        {
            propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly ObservableCollection<string> _availableOptions;
    public ObservableCollection<string> AvailableOptions
    {
        get
        {
            return _availableOptions;
        }
    }

    private string _selectedOption;
    public string SelectedOption
    {
        get { return _selectedOption; }
        set
        {
            if (_selectedOption == value)
            {
                return;
            }
            _selectedOption = value;
            RaisePropertyChanged("SelectedOption");
        }
    }
}

复制步骤:
1) 运行应用程序
2) 打开组合框(以便呈现下拉选项)
3)点击“重新加载模型”按钮

此时将有两个 ViewModel 对象,较旧的、意外的实例的根源如下: ViewModel->PopupRoot->Popup->ComboBox->MainWindow->App

这是一个错误还是我做错了?

埃蒙

【问题讨论】:

  • 你能用一个计时器来检测你的重新加载方法,让它重复几个小时,看看它是否真的是泄漏?还是只是 GC 需要赶上?
  • 这不是真正意义上的泄漏,因为它是有界的,但是第一个 ViewModel 对象永远不会被收集,无论您单击“重新加载模型”多少次,它都始终由 PopupRoot 对象扎根。所有后续创建的 ViewModel 都会在下一个加载后被收集。
  • 感谢您的澄清。这不是失控的泄漏,而是“孤立的”数据上下文。在您的 MainWindow 构造函数中,您能否将最后两行替换为对 reload 方法的一次调用?
  • 这没什么区别。似乎 PopupRoot 在第一次打开时继承了 ComboBox 的 DataContext ,之后当组合框的 DataContext 更改时它不再接收更新。我发现另一个问题与菜单表现出类似的行为(PopupRoot 也是罪魁祸首)stackoverflow.com/q/17239406/718033
  • 您找到解决方案了吗?我有巨大的内存问题,因为弹出窗口和 ContextMenus 保留了对我所有 ViewModel 和 Views 的引用......这使我的整个应用程序基本上没有垃圾收集!

标签: c# wpf memory-leaks combobox


【解决方案1】:

Joe 的评论将我的注意力带回了这个我已经为自己解决的老问题。最后我写了一个行为,我可以将它附加到一个处理内存泄漏的组合框。

我已经在这里发布了代码:https://github.com/EamonHetherton/Demos/blob/master/StackOverflow/18096050/StopComboBoxMemoryLeakBehaviour.cs

购买者警告:此解决方案依赖于反思和可能带来的脆弱性。它对我有用,YMMV。

【讨论】:

    【解决方案2】:

    最近我遇到了几个与Popup / ContextMenu / ComboBox与DataContext绑定有关的内存泄漏问题。

    我发现Popup / ComboBox的问题本质上是“_popupRoot”的DataContext在其父级的DataContext设置为null后没有释放。

    对于 ContextMenu,如果它与某种 ItemsSource 绑定生成的控件一起使用,那么 WPF 会缓存 Contextmenu,所以它的 DataContext 不会被释放,除非用户右键单击再次在某个地方弹出 ContextMenu。

    我设法创建了 3 个派生类来替换使用 DataContext 绑定的 WPF 控件。我将它们粘贴在这里,希望它们对其他人有用。

    public class ComboBoxFixMem : ComboBox
    {
        public ComboBoxFixMem()
        {
            this.DataContextChanged += ComboBox_DataContextChanged;
        }
    
        private void ComboBox_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.DataContext != null)
                return;
            FrameworkElement fe = this.GetTemplateChild("PART_Popup") as FrameworkElement;
            if (null != fe)
                fe.DataContext = null;
            PopupFixMem.ClearPopupDataContext(fe as Popup);
        }
    }
    
    public class ContextMenuFixMem : ContextMenu
    {
        protected override void OnClosed(RoutedEventArgs e)
        {
            base.OnClosed(e);
            FrameworkElement p = this.Parent as FrameworkElement;
            if (null != p)
                p.DataContext = null;
        }
    }
    
    public class PopupFixMem : Popup
    {
        public PopupFixMem()
        {
            this.DataContextChanged += Popup_DataContextChanged;
        }
    
        private void Popup_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (this.DataContext != null)
                return;
            ClearPopupDataContext(this);
        }
    
        public static void ClearPopupDataContext(Popup popup)
        {
            if (null == popup)
                return;
            try
            {
                var fiPopupRoot = typeof(Popup).GetField("_popupRoot", BindingFlags.NonPublic | BindingFlags.Instance);
                var popupRootWrapper = fiPopupRoot?.GetValue(popup);
                if (null == popupRootWrapper)
                    return;
                var valueFieldInfo = popupRootWrapper.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance);
                var popupRoot = valueFieldInfo?.GetValue(popupRootWrapper, new object[0]) as FrameworkElement;
                if (null != popupRoot)
                    popupRoot.DataContext = null;
            }
            catch (Exception) { }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-01
      • 2011-02-21
      • 1970-01-01
      • 2010-12-05
      • 2011-03-19
      相关资源
      最近更新 更多