WPF:评估XAML绑定超出顶级自定义对象

时间:2018-10-24 17:44:13

标签: wpf xaml

在我的xaml中,我声明了一个自定义对象,该对象具有引用另一个自定义对象的属性:

public class CustomObjectA : FrameworkElement
{
   public CustomObjectB InnerObj
   {
      get { return GetValue(InnerObjProperty); }
      set { SetValue(InnerObjProperty, value); }
   }

   public static readonly DependencyProperty InnerObjProperty = 
                          DependencyProperty.Register("InnerObj",
                                                      typeof(CustomObjectB),
                                                      typeof(CustomObjectA),
                                                      new PropertyMetadata(null));
}

public class CustomObjectB : FrameworkElement
{
   public string Data
   {
      get { return GetValue(DataProperty); }
      set { SetValue(DataProperty, value); }
   }

   public static readonly DependencyProperty DataProperty = 
                          DependencyProperty.Register("Data",
                                                      typeof(string),
                                                      typeof(CustomObjectB),
                                                      new PropertyMetadata(null));
}

现在,当我像这样在xaml中声明这些对象时,绑定不起作用:

<my:CustomObjectA>
   <my:CustomObjectA.InnerObj>
      <my:CustomObjectB Data="{Binding someValue}" />
   </my:CustomObjectA.InnerObj>
</my:CustomObjectA>

但是,当我像这样在xaml中声明这些对象时,绑定起作用:

<my:CustomObjectB x:Name="testObj" Data="{Binding someValue}" />

<my:CustomObjectA InnerObj="{Binding ElementName=testObj}" />

我假设这是因为映射绑定的系统看上去不会越过顶层对象。我的问题是;有没有办法告诉系统评估顶级定制对象之外的绑定表达式,以便像选项1这样的xaml起作用?

1 个答案:

答案 0 :(得分:0)

DataContext没有向下传递给InnerObj。当InnerObj更改时,我通过更新DataContext使它起作用:

public class CustomObjectA : FrameworkElement
{
    public CustomObjectB InnerObj
    {
        get { return (CustomObjectB)GetValue(InnerObjProperty); }
        set { SetValue(InnerObjProperty, value); }
    }

    public static readonly DependencyProperty InnerObjProperty =
                           DependencyProperty.Register("InnerObj",
                                                       typeof(CustomObjectB),
                                                       typeof(CustomObjectA),
                                                       new FrameworkPropertyMetadata(OnInnerObjUpdated));

    private static void OnInnerObjUpdated(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var local = (CustomObjectA)d;
        var newObj = (CustomObjectB)e.NewValue;

        newObj.DataContext = local.DataContext;
    }
}