跟进这个问题。
显然,由于某种原因,在显式设置Parent.Child
属性(在构造函数内部或显式构造函数外部)之后,当我设置对象的Child.Trigger
属性时Parent.Child
,Parent.Child
对象又被设置了。这可以通过中断_OnChildChanged
静态构造函数中定义的方法来观察。在它被调用的第二个实例中,您可以看到它e.OldValue
不为空,并且它与e.NewValue
.
为什么设置Child
属性Parent
时又设置了Trigger
属性?
符合必要的最小、完整和可验证示例:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media.Animation;
namespace MCVE {
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class Program {
[STAThread]
public static int Main( ) {
Parent p = new Parent( );
p.Child.Trigger = new object( );
return 0;
}
}
public abstract class Base : Animatable {
public static readonly DependencyProperty TriggerProperty;
static Base( ) =>
TriggerProperty = DependencyProperty.Register(
"Trigger", typeof( object ), typeof( Base) );
public object Trigger {
get => this.GetValue( TriggerProperty );
set => this.SetValue( TriggerProperty, value );
}
}
public class Parent : Base {
public static readonly DependencyProperty ChildProperty;
static Parent( ) {
ChildProperty = DependencyProperty.Register(
"Child", typeof( Child ), typeof( Parent ),
new PropertyMetadata( null as Child, _OnChildChanged ) );
void _OnChildChanged(
DependencyObject sender,
DependencyPropertyChangedEventArgs e ) =>
Console.WriteLine( "Child Changed!" );
}
public Parent( ) : base( ) =>
this.Child = new Child( );
public Child Child {
get => this.GetValue( ChildProperty ) as Child;
set => this.SetValue( ChildProperty, value );
}
protected override Freezable CreateInstanceCore( ) => new Parent( );
}
public class Child : Base {
public Child( ) : base( ) { }
protected override Freezable CreateInstanceCore( ) => new Child( );
}
}
重现:
- 创建 WPF 项目。目标.Net 4.7.2。
- 选择
App.xaml
- 在 下
Properties
,更改Build Action
为Page
- 将代码粘贴到
App.xaml.cs
. 覆盖一切。