在定义继承Animatable
类的基类时,我发现自己发现了一些奇怪的行为。
当我在“父”类中创建子DependencyProperty时,然后定义该“父”类的实例,然后更改父子上的属性,我为“父子”属性定义的PropertyChangedCallback将触发。
符合必要的Minimal, Complete and Verifiable Example:
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( );
}
}
要复制:
App.xaml
Properties
下,将Build Action
更改为Page
App.xaml.cs
中。覆盖所有内容。运行此代码,您应该在控制台中看到两次打印该消息。
为什么会这样?有办法阻止它发生吗?
关注Here:
答案 0 :(得分:1)
由于将Child属性设置为2次,因此在控制台中将消息打印2次:
我认为在您的情况下,您可以在_OnChildChanged()中比较Child属性的新值和旧值,以防止出现此问题:
void _OnChildChanged(
DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
if (e.NewValue != e.OldValue)
{
Console.WriteLine("Child Changed!");
}
}
致谢!