この質問に続きます。
どうやら、Parent.Child
プロパティを明示的に設定した後 (コンストラクター内またはコンストラクターの外側で明示的に)、オブジェクトのChild.Trigger
プロパティを設定すると、オブジェクトが再び設定されているようです。これは、静的コンストラクター内で定義されたメソッドを中断することで確認できます。呼び出された 2 番目のインスタンスでは、 が null ではなく、 と同じであることがわかります。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
。すべてを上書きします。