WPF + PostSharp'ed View模型在一分钟内冻结

问题描述 投票:2回答:1

更新(见下文)

经过一分钟的密集工作后,WPF开始忽略属性更改通知。这是一个重现的演示(也在GitHub上)。查看模型是:

[Aggregatable]
[NotifyPropertyChanged]
[ContentProperty("Tests")]
public class Model
{
    [Child] public AdvisableCollection<Test> Tests { get; } = new AdvisableCollection<Test>();
    [Child] public Test Test { get; set; }
}

哪里:

[Aggregatable]
[NotifyPropertyChanged]
public class Test
{
    public string Name { get; set; }
    [Parent] public Model Model { get; private set; }
}

XAML:

<Window x:Class="Demo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Demo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:Model>
            <local:Test Name="a"/>
            <local:Test Name="b"/>
            <local:Test Name="c"/>
            <local:Test Name="d"/>
        </local:Model>
    </Window.DataContext>
    <TextBox DockPanel.Dock="Top" Text="{Binding Test.Name, Mode=OneWay}"/>
</Window>

而背后的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        Timer = new DispatcherTimer();
        Timer.Interval = TimeSpan.FromMilliseconds(250);
        Timer.Tick += Timer_Tick;
        Timer.Start();
    }

    DispatcherTimer Timer { get; }
    Random Random = new Random();
    Model Model => DataContext as Model;

    private void Timer_Tick(object sender, EventArgs e)
    {
        var i = Random.Next(Model.Tests.Count);
        Model.Test = Model.Tests[i];
    }
}

运行它并等一下 - 窗口将被冻结。任何想法如何解决它?

UPDATE

我简化了模型 - 这个模型在一分钟内仍然被冻结:

[NotifyPropertyChanged]
[ContentProperty("Tests")]
public class Model
{
    public List<Test> Tests { get; } = new List<Test>();
    public Test Test { get; set; }
}

[NotifyPropertyChanged]
public class Test
{
    public string Name { get; set; }
}

但是以下版本的Test类解决了这个问题:

public class Test : INotifyPropertyChanged
{
    public string Name { get; set; }

    public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
c# wpf inotifypropertychanged postsharp .net-4.7.2
1个回答
3
投票

看起来这个问题是由NotifyPropertyChanged方面的弱事件管理器与WPF中的弱事件管理器之间的不兼容引起的。作为解决方法,您可以在将方面应用于目标元素时禁用方面的弱事件实现:

[NotifyPropertyChanged( WeakEventStrategy = WeakEventStrategy.AlwaysStrong )]
[ContentProperty("Tests")]
public class Model
{
    // ...
}

[NotifyPropertyChanged( WeakEventStrategy = WeakEventStrategy.AlwaysStrong )]
public class Test
{
    // ...
}

我们将继续调查此问题,一旦修复程序发布,我们将更新答案。

编辑:此问题已在PostSharp 6.0.28中修复。

© www.soinside.com 2019 - 2024. All rights reserved.