为什么绑定到祖先比按名称绑定到元素或绑定到 DataContext 更晚?

Why binding to an ancestor becomes active later than binding to an element by its name or binding to the DataContext?

我在尝试在代码中短时间设置绑定时注意到了这一点。其实我只是想获取绑定提供的值。所以我设置绑定,获取目标 属性 的值并立即清除绑定。在为绑定设置模式为 FindAncestor 的 RelativeSource 之前,一切都很好。在这种情况下目标 属性 returns 它的默认值。

经过一些调试后,我发现 FindAncestor 绑定的 BindingExpression 的 属性 状态设置为未附加。对于其他类型的绑定,BindingExpression.Status 设置为活动。

我写了一些代码来说明这一点。

Window1.xaml

<Window x:Class="Wpf_SetBindingInCode.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Name="Window"
        Title="Window1"
        Height="300" Width="300"
        DataContext="DataContext content">
    <StackPanel>
        <Button Content="Set binding" Click="SetBindingButtonClick"/>
        <TextBlock x:Name="TextBlock1"/>
        <TextBlock x:Name="TextBlock2"/>
        <TextBlock x:Name="TextBlock3"/>
    </StackPanel>
</Window>

Window1.xaml.cs

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void SetBindingButtonClick(object sender, RoutedEventArgs e)
    {
        Binding bindingToRelativeSource = new Binding("DataContext")
        {
            RelativeSource = new RelativeSource { Mode = RelativeSourceMode.FindAncestor, AncestorType = typeof(Window1) },
        };
        Binding bindingToElement = new Binding("DataContext")
        {
            ElementName = "Window"
        };
        Binding bindingToDataContext = new Binding();

        BindingOperations.SetBinding(TextBlock1, TextBlock.TextProperty, bindingToRelativeSource);
        BindingOperations.SetBinding(TextBlock2, TextBlock.TextProperty, bindingToElement);
        BindingOperations.SetBinding(TextBlock3, TextBlock.TextProperty, bindingToDataContext);

        Trace.WriteLine("TextBlock1.Text = \"" + TextBlock1.Text + "\"");
        Trace.WriteLine("TextBlock2.Text = \"" + TextBlock2.Text + "\"");
        Trace.WriteLine("TextBlock3.Text = \"" + TextBlock3.Text + "\"");

        var bindingExpressionBase1 = BindingOperations.GetBindingExpressionBase(TextBlock1, TextBlock.TextProperty);
        var bindingExpressionBase2 = BindingOperations.GetBindingExpressionBase(TextBlock2, TextBlock.TextProperty);
        var bindingExpressionBase3 = BindingOperations.GetBindingExpressionBase(TextBlock3, TextBlock.TextProperty);

        Trace.WriteLine("bindingExpressionBase1.Status = " + bindingExpressionBase1.Status);
        Trace.WriteLine("bindingExpressionBase2.Status = " + bindingExpressionBase2.Status);
        Trace.WriteLine("bindingExpressionBase3.Status = " + bindingExpressionBase3.Status);
    }
}

上面的代码产生以下输出:

TextBlock1.Text = ""
TextBlock2.Text = "DataContext content"
TextBlock3.Text = "DataContext content"
bindingExpressionBase1.Status = Unattached
bindingExpressionBase2.Status = Active
bindingExpressionBase3.Status = Active

但是尽管如此,表单上的所有三个 TextBlock 都具有预期值 - "DataContext content"。

所以我的问题是:

  1. 为什么RelativeSourceMode.FindAncestor绑定不提供 BindingOperations.SetBinding(...) 被调用后的值?

  2. 有没有办法强制这种绑定更新目标 属性?我试着打电话给 bindingExpression.UpdateTarget() - 它 没有像预期的那样工作。

这是设计使然。要了解原因,让我们看一下代码。

Expression 设置为 DependencyProperty 的值时,调用 Expression.OnAttach (source). This method is overriden in the BindingExpressionBase class (source):

internal sealed override void OnAttach(DependencyObject d, DependencyProperty dp)
{
    if (d == null)
        throw new ArgumentNullException("d");
    if (dp == null)
        throw new ArgumentNullException("dp");

    Attach(d, dp);
}

internal void Attach(DependencyObject target, DependencyProperty dp)
{
    // make sure we're on the right thread to access the target
    if (target != null)
    {
        target.VerifyAccess();
    }

    IsAttaching = true;
    AttachOverride(target, dp);
    IsAttaching = false;
}

AttachOverride 方法也是虚拟的,它在 BindingExpression (source) 中被覆盖。

internal override bool AttachOverride(DependencyObject target, DependencyProperty dp)
{
    if (!base.AttachOverride(target, dp))
        return false;

    // listen for InheritanceContext change (if target is mentored)
    if (ParentBinding.SourceReference == null || ParentBinding.SourceReference.UsesMentor)
    {
        DependencyObject mentor = Helper.FindMentor(target);
        if (mentor != target)
        {
            InheritanceContextChangedEventManager.AddHandler(target, OnInheritanceContextChanged);
            UsingMentor = true;

            if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.Attach))
            {
                TraceData.Trace(TraceEventType.Warning,
                                    TraceData.UseMentor(
                                        TraceData.Identify(this),
                                        TraceData.Identify(mentor)));
                }
            }
        }

        // listen for lost focus
        if (IsUpdateOnLostFocus)
        {
            Invariant.Assert(!IsInMultiBindingExpression, "Source BindingExpressions of a MultiBindingExpression should never be UpdateOnLostFocus.");
            LostFocusEventManager.AddHandler(target, OnLostFocus);
        }

        // attach to things that need tree context.  Do it synchronously
        // if possible, otherwise post a task.  This gives the parser et al.
        // a chance to assemble the tree before we start walking it.
        AttachToContext(AttachAttempt.First);
        if (StatusInternal == BindingStatusInternal.Unattached)
        {
            Engine.AddTask(this, TaskOps.AttachToContext);

            if (TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.AttachToContext))
            {
                TraceData.Trace(TraceEventType.Warning,
                                    TraceData.DeferAttachToContext(
                                        TraceData.Identify(this)));
        }
    }

    GC.KeepAlive(target);   // keep target alive during activation (bug 956831)
    return true;
}

在列出的代码中我们可以看到在所有动作之后BindingExpression仍然可以Unattached。让我们看看为什么在我们的情况下会这样。为此,我们需要确定状态更改的位置。这可以通过 IL Spy 完成,它显示 AttachToContext (source).

中的状态已更改
// try to get information from the tree context (parent, root, etc.)
// If everything succeeds, activate the binding.
// If anything fails in a way that might succeed after further layout,
// just return (with status == Unattached).  The binding engine will try
// again later. For hard failures, set an error status;  no more chances.
// During the "last chance" attempt, treat all failures as "hard".
void AttachToContext(AttachAttempt attempt)
{
    // if the target has been GC'd, just give up
    DependencyObject target = TargetElement;
    if (target == null)
        return;     // status will be Detached

    bool isExtendedTraceEnabled = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.AttachToContext);
    bool traceObjectRef = TraceData.IsExtendedTraceEnabled(this, TraceDataLevel.SourceLookup);

    // certain features should never be tried on the first attempt, as
    // they certainly require at least one layout pass
    if (attempt == AttachAttempt.First)
    {
        // relative source with ancestor lookup
        ObjectRef or = ParentBinding.SourceReference;
        if (or != null && or.TreeContextIsRequired(target))
        {
            if (isExtendedTraceEnabled)
            {
                TraceData.Trace(TraceEventType.Warning,
                                    TraceData.SourceRequiresTreeContext(
                                        TraceData.Identify(this),
                                        or.Identify()));
            }

            return;
        }
    }

评论中说某些功能至少需要一次布局传递,其中之一是 RelativeSource 具有祖先查找 (source)。

internal bool TreeContextIsRequired(DependencyObject target)
{
    return ProtectedTreeContextIsRequired(target);
}

/// <summary> true if the ObjectRef really needs the tree context </summary>
protected override bool ProtectedTreeContextIsRequired(DependencyObject target)
{
    return  (   (_relativeSource.Mode == RelativeSourceMode.FindAncestor
        ||  (_relativeSource.Mode == RelativeSourceMode.PreviousData)));
}

因为 RelativeSource 需要树上下文,所以 BindingExpressionUnattached。因此 属性 值不会立即更新。

在任何 UIElement 上调用 UpdateLayout 以强制更新布局并附加 BindingExpression