【发布时间】:2018-07-04 11:27:24
【问题描述】:
dotMemory 告诉我(下面的屏幕截图,“WPF 绑定泄漏”)像这样绑定到字典时存在内存泄漏:
<ComboBox ItemsSource="{Binding Items, Mode=OneTime}"
DisplayMemberPath="Value"
SelectedValue="{Binding SelectedItem}"
SelectedValuePath="Key" />
问题一,给大家:为什么是内存泄漏(即我应该使用什么场景来遇到问题)以及如何解决它?
Queston 2,致 dotMemory 专家:为什么这么基本的 mvvm 应用程序(见下文)报告了这么多问题?我应该解决这些问题吗?怎么样?
MCVE(创建新的 WPF 解决方案,在 xaml 中使用上述代码)代码后面:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string property = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
public Dictionary<string, string> Items { get; } = new Dictionary<string, string>
{
{ "1", "One" },
{ "1a", "One and a" },
{ "2a", "Two and a" },
};
string _selectedItem = "1a";
public string SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged();
}
}
}
【问题讨论】:
-
旁注,绑定到字典很糟糕,因为绑定不知道 jack 对字典的了解,所以它们将它们视为 IEnumerable
>。因此,您会失去自动 DataTemplate 选择等 WPF 功能。使用实现 INotifyCollectionChanged 的 KeyedCollection 是一个更好的主意,因为它实现了 IEnumerable 。另外, 16b也不用担心:/
标签: c# wpf mvvm memory-leaks dotmemory