dotMemory
告诉我(下面的屏幕截图,“WPF 绑定泄漏”)绑定到字典时存在内存泄漏,如下所示:
<ComboBox ItemsSource="{Binding Items, Mode=OneTime}"
DisplayMemberPath="Value"
SelectedValue="{Binding SelectedItem}"
SelectedValuePath="Key" />
问题1,给大家:为什么是内存泄漏(即我应该使用什么场景来遇到问题)以及如何解决它?
问题 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();
}
}
}