【问题标题】:WPF: Evaluate XAML binding beyond top level custom objectWPF:评估顶级自定义对象之外的 XAML 绑定
【发布时间】:2018-10-24 17:44:13
【问题描述】:

在我的 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 可以工作?

【问题讨论】:

  • 我可以检查一下,如果它有效,我可能会发布一个答案 - 但我最初的感觉是数据上下文没有被传递给 objectB,因此当你在对象之外有绑定时正确绑定。

标签: wpf xaml


【解决方案1】:

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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多