使用PostSharp跟踪属性更改
我想在所有前面的页面有效时启用给定的向导页面。 这是我的视图模型:
[Aggregatable] [NotifyPropertyChanged] [ContentProperty("Pages")] public class Wizard { [Child, AggregateAllChanges] public AdvisableCollection Pages { get; } = new AdvisableCollection(); }
这是Page
本身:
[Aggregatable] [NotifyPropertyChanged] public class Page : INotifyPropertyChanged { [Parent] Wizard Wizard { get; set; } public string Name { get; set; } public bool Valid { get; set; } [SafeForDependencyAnalysis] public bool Enabled { get { if(Depends.Guard) Depends.On(Wizard.Pages); return Wizard.Pages .TakeWhile(p => p != this) .All(p => p.Valid); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; void OnPropertyChanged(string propertyName) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); if (Wizard != null) NotifyPropertyChangedServices.SignalPropertyChanged(Wizard, nameof(Wizard.Pages)); } }
我期待PostSharp在Wizard.Pages
更改时通知有关已Enabled
属性更改。 遗憾的是它不起作用 – Enabled
属性没有更新。 这段代码有什么问题?
XAML测试:
我们已经调查了提供的示例,看起来原因是NotifyPropertyChanged
和Aggregatable
方面之间的兼容性问题。
如果删除或注释掉[Aggregatable]
属性,则会按预期为Enabled
属性引发事件。 实际上,甚至可以将Wizard
属性标记为引用,而不是父级来修复NPC行为。 一旦Wizard
属性未标记为父级,您需要通过手动设置属性来确保正确的值。
请注意,您还需要在OnPropertyChanged
方法中添加属性名称检查以避免无限循环“Wizard.Pages已更改” – >“已启用已更改” – >“Wizard.Pages已更改”…
[Aggregatable] [NotifyPropertyChanged] public class Page : INotifyPropertyChanged { //[Parent] [Reference] public Wizard Wizard { get; set; } public string Name { get; set; } public bool Valid { get; set; } [SafeForDependencyAnalysis] public bool Enabled { get { if ( Depends.Guard ) Depends.On( Wizard.Pages ); return Wizard.Pages .TakeWhile( p => p != this ) .All( p => p.Valid ); } } public event PropertyChangedEventHandler PropertyChanged = delegate { }; void OnPropertyChanged( string propertyName ) { PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) ); if ( Wizard != null && propertyName != nameof( Enabled ) ) NotifyPropertyChangedServices.SignalPropertyChanged( Wizard, nameof( Wizard.Pages ) ); } }
我们将继续调查此问题,我们将在修复发布后更新答案。
UPDATE。 PostSharp版本6.0.29中修复了NotifyPropertyChanged
和Aggregatable
方面之间的兼容性错误。 请将您的NuGet包更新到最新版本。