カスタム WPF DependencyObject で DependencyProperty の値の継承を実装しようとしていますが、ひどく失敗しています:(
私がしたいこと:
両方の DependencyProperty IntTestを持つT1とT2の 2 つのクラスがあり、デフォルトは 0 です。T1 は T2 のルートである必要があります。これは、Window がそれに含まれる TextBox の論理ルート/親であるのと同じです。
したがって、T2.IntTest の値を明示的に設定しない場合は、T1.IntTestの値を提供する必要があります(たとえば、TextBox.FlowDirection が通常、親ウィンドウの FlowDirection を提供するように)。
私がしたこと:
FrameworkPropertyMetadataOptions.InheritsでFrameworkPropertyMetadataを使用するために、FrameworkElement から派生する 2 つのクラス T1 と T2 を作成しました。また、値の継承を使用するには、DependencyProperty を AttachedProperty として設計する必要があることも読みました。
現在、ルート T1 に値を割り当てると、子 T2 の DP-Getter によって値が返されません。
私は何を間違っていますか???
次の 2 つのクラスがあります。
// Root class
public class T1 : FrameworkElement
{
// Definition of an Attached Dependency Property
public static readonly DependencyProperty IntTestProperty = DependencyProperty.RegisterAttached("IntTest", typeof(int), typeof(T1),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
// Static getter for Attached Property
public static int GetIntTest(DependencyObject target)
{
return (int)target.GetValue(IntTestProperty);
}
// Static setter for Attached Property
public static void SetIntTest(DependencyObject target, int value)
{
target.SetValue(IntTestProperty, value);
}
// CLR Property Wrapper
public int IntTest
{
get { return GetIntTest(this); }
set { SetIntTest(this, value); }
}
}
// Child class - should inherit the DependenyProperty value of the root class
public class T2 : FrameworkElement
{
public static readonly DependencyProperty IntTestProperty = T1.IntTestProperty.AddOwner(typeof(T2),
new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
public int IntTest
{
get { return (int)GetValue(IntTestProperty); }
set { SetValue(IntTestProperty, value); }
}
}
そして、これを試すコードは次のとおりです。
T1 t1 = new T1();
T2 t2 = new T2();
// Set the DependencyProperty of the root
t1.IntTest = 123;
// Do I have to build a logical tree here? If yes, how?
// Since the DependencyProperty of the child was not set explicitly,
// it should provide the value of the base class, i.e. 123.
// But this does not work: i remains 0 :((
int i = t2.IntTest;