小编Pet*_*ter的帖子

Border.Effect绑定泄漏内存但Border.Background没有

使用更新的.NET 4.0,我发现了一个奇怪的内存泄漏,可以通过以下示例代码重现.

  • app.xml有一些应用程序范围的资源,它们绑定到app.xml.cs中的属性.创建泄漏的资源是<DropShadowEffect>Color依赖项属性绑定到App对象中的属性.
  • 主窗口有一个按钮,用于启动LeakWindow,其中使用app.xml中定义的资源.
  • 当泄漏窗口关闭时,它不会被垃圾收集.只有在泄漏窗口使用上述DropShadowEffect资源时才会发生这种情况.不会发生在一个SolidColorBrushColor也必然同一来源.

真的很感激,如果有人能告诉我为什么这个泄漏发生在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)

c# wpf

7
推荐指数
1
解决办法
301
查看次数

当我绑定到 IEnumerable 时,WPF 如何知道使用 INotifyPropertyChanged?

在视图模型(SomeViewModel如下)中,Data属性返回IEnumerable<IData>两个接口都没有实现的地方INotifyPropertyChanged

但是,底层的 Data 字段是ObservableCollection<ObservableData>并且两个类都实现了INotifyPropertyChanged.

最后,在 XAML 中,`Data 绑定到 DataGrid。

<Da​​taGrid 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)

c# wpf

3
推荐指数
2
解决办法
842
查看次数

标签 统计

c# ×2

wpf ×2