使用更新的.NET 4.0,我发现了一个奇怪的内存泄漏,可以通过以下示例代码重现.
<DropShadowEffect>其Color依赖项属性绑定到App对象中的属性.DropShadowEffect资源时才会发生这种情况.不会发生在一个SolidColorBrush其Color也必然同一来源.真的很感激,如果有人能告诉我为什么这个泄漏发生在DropShadowEffect但不是在SolidColorBrush?
app.xml中
<Application x:Class="WpfSimple.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
<!--this one make GC unable to collect LeakWindow-->
<DropShadowEffect x:Key="AppDropShadowColor"
Color="{Binding Source={x:Static Application.Current}, Path=DropShadowColor, Mode=OneWay}" />
<!--this one does not leak-->
<SolidColorBrush x:Key="AppBackground"
Color="{Binding Source={x:Static Application.Current}, Path=DropShadowColor, Mode=OneWay}" />
</Application.Resources>
</Application>
Run Code Online (Sandbox Code Playgroud)
App.xml.cs启动MainWindow并INotifyPropertyChanged为该属性实现DropShadowColor.
public partial class App : Application, INotifyPropertyChanged
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// …Run Code Online (Sandbox Code Playgroud) 在视图模型(SomeViewModel如下)中,Data属性返回IEnumerable<IData>两个接口都没有实现的地方INotifyPropertyChanged。
但是,底层的 Data 字段是ObservableCollection<ObservableData>并且两个类都实现了INotifyPropertyChanged.
最后,在 XAML 中,`Data 绑定到 DataGrid。
<DataGrid ItemsSource="{绑定数据}" AutoGenerateColumns="True"/>
我认为此绑定可能会引入KB938416 中描述的绑定内存泄漏,但令我惊讶的是它没有。
当该方法ChangeData被调用时,我可以看到 DataGrid 被更新并且被OnPropertyChanged调用了一个处理程序。
我的问题是:WPF 如何知道INotifyPropertyChanged在绑定数据返回时使用IEnumerable<IData>(两者都没有实现 INotifyPropertyChanged)??
public interface IData
{
string Name { get; }
}
// In addition to IData, implements INotifyPropertyChanged
public class ObservableData : IData, INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return this._name; }
set
{ …Run Code Online (Sandbox Code Playgroud)