1

この質問に続きます。

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

再現するには:

  1. WPF プロジェクトを作成します。ターゲット.Net 4.7.2。
  2. 選択するApp.xaml
  3. の下Propertiesで、に変更Build ActionしますPage
  4. にコードを貼り付けますApp.xaml.cs。すべてを上書きします。
4

1 に答える 1