【发布时间】:2019-05-23 22:59:08
【问题描述】:
跟进this问题。
显然,由于某种原因,在显式设置 Parent.Child 属性(在构造函数内部或显式构造函数外部)之后,当我设置 Parent.Child 对象的 Child.Trigger 属性时,Parent.Child 对象再次设置。这可以通过破坏静态构造函数中定义的_OnChildChanged 方法来观察。在第二次调用它时,您可以看到e.OldValue 不为空,并且与e.NewValue 相同。
为什么在设置Trigger 属性时再次设置Parent 的Child 属性?
符合必要的 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( );
}
}
复制:
- 创建 WPF 项目。目标 .Net 4.7.2。
- 选择
App.xaml - 在
Properties下,将Build Action更改为Page - 将代码粘贴到
App.xaml.cs。覆盖所有内容。
【问题讨论】:
-
作为说明,在Trigger属性的注册中使用
typeof(Parent)是错误的,因为注册属性的类是Base。您也不需要用于注册的静态构造函数。写public static readonly DependencyProperty TriggerProperty = DependencyProperty.Register(nameof(Trigger), typeof(object), typeof(Base)); -
@Clemens:粗鲁。复制粘贴留下的工件。更新了代码。
标签: c# wpf xaml dependency-properties dependencyobject