假设我有两个类可以引用第三个 UI 对象(在本例中为按钮)。
此外,父类可以包含子类的元素。
如果它们都绑定到同一个控件,以同样的方式,孩子会失败,但父母会成功。
这是 WPF 中的错误吗?
家长:
class MyFrameworkElement : FrameworkElement
{
// A depenedency property that will contain a child element sub-element
private static readonly DependencyProperty ChildElementProperty =
DependencyProperty.Register("ChildElement",
typeof(MyChildElement),
typeof(MyFrameworkElement),
new PropertyMetadata());
[Category("ChildProperties")]
public MyChildElement ChildElement
{
set { SetValue(ChildElementProperty, value); }
get { return (MyChildElement)GetValue(ChildElementProperty); }
}
// Now, a reference to some other control, in this case we will bind a button to it!
public UIElement ButtonReferenceInParent
{
get { return (UIElement)GetValue(ButtonReferenceInParentProperty); }
set { SetValue(ButtonReferenceInParentProperty, value); }
}
// Using a DependencyProperty as the backing store for ButtonReferenceInParent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ButtonReferenceInParentProperty =
DependencyProperty.Register("ButtonReferenceInParent", typeof(UIElement), typeof(MyFrameworkElement), new UIPropertyMetadata(null));
然后是孩子:
public class MyChildElement : FrameworkElement
{
public UIElement ButtonReferenceInChild
{
get { return (UIElement)GetValue(ButtonReferenceInChildProperty); }
set { SetValue(ButtonReferenceInChildProperty, value); }
}
public static readonly DependencyProperty ButtonReferenceInChildProperty =
DependencyProperty.Register("ButtonReferenceInChild", typeof(UIElement), typeof(MyChildElement), new UIPropertyMetadata(null));
}
好的 -
现在说我像这样将它们添加到我的 XAML 中:
<Grid>
<my:MyFrameworkElement x:Name="ParentName" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ButtonReferenceInParent="{Binding ElementName=buttonisme}">
<my:MyFrameworkElement.ChildElement>
<my:MyChildElement x:Name="ChildName" ButtonReferenceInChild="{Binding ElementName=buttonisme}"/>
</my:MyFrameworkElement.ChildElement>
</my:MyFrameworkElement>
<Button x:Name="buttonisme" Click="buttonisme_Click" />
</Grid>
当我使用完全相同的表示法时,为什么绑定在父级上有效,但在子级上失败?
这是我的测试代码...
Console.WriteLine("Parent button reference is {0}", ParentName.ButtonReferenceInParent);
if (ChildName.ButtonReferenceInChild == null)
{
Console.WriteLine("Child button reference is null!");
}
else
{
Console.WriteLine("Child button is {0}", ChildName.ButtonReferenceInChild);
}
这是测试结果...
父按钮引用是 System.Windows.Controls.Button
子按钮引用为空!