0

我正在编写一些以编程方式动态创建绑定的代码,但我似乎无法读取将 RelativeSourceMode 设置为 FindAncestor 的绑定所产生的值。我想知道是否有人使用这种模式成功地在代码(不是 XAML)中创建了 RelativeSource 绑定?

打开绑定跟踪后,警告为:

System.Windows.Data 警告:64:BindingExpression (hash=57957548):RelativeSource (FindAncestor) 需要树上下文

这是创建 RelativeSource 绑定的示例代码:

 private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
 {
        // Create RelativeSource FindAncestor Binding
        var binding = new Binding
                             {
                                 RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1),
                                 Path = new PropertyPath("Tag"),
                             };

        PresentationTraceSources.SetTraceLevel(binding, PresentationTraceLevel.High);
        BindingOperations.SetBinding(textBlock, TagProperty, binding);

        // Always null
        var findAncestorBindingResult = textBlock.Tag;

        // Create RelativeSource Self Binding
        binding = new Binding
        {
            RelativeSource = new RelativeSource(RelativeSourceMode.Self),
            Path = new PropertyPath("Text"),
        };

        PresentationTraceSources.SetTraceLevel(binding, PresentationTraceLevel.High);
        BindingOperations.SetBinding(textBlock, TagProperty, binding);

        // Has correct value Text property set from XAML
        var selfBindingResult = textBlock.Tag;
    }

这是相应的 XAML:

    <StackPanel>
        <ListBox x:Name="listBox">
            <ListBoxItem x:Name="listBoxItem" Tag="Item One" >
                <ListBoxItem.Content>
                    <TextBlock x:Name="textBlock">
                        <TextBlock.Text>
                            <Binding RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}" Path="Tag" />
                        </TextBlock.Text>
                    </TextBlock>
                </ListBoxItem.Content>
            </ListBoxItem>
        </ListBox>
        <Button Content="Debug" Click="ButtonBase_OnClick" />
    </StackPanel>

树已加载,因此我可以模拟 FindAncestor 绑定(VisualTreeHelper.GetParent(...)用于定位 FindAncestor 绑定的目标元素,然后对其应用 RelativeSource Self 绑定)但我很好奇为什么这不起作用。

提前致谢!

4

1 回答 1

1

绑定后您无法立即获取绑定属性的值,您当前正在使用处理程序操作阻塞 UI 线程,绑定只会在线程空闲时发生(我认为)。

您应该删除Always null注释后的所有内容并稍后检查值,例如在另一个按钮的处理程序中。此外,绑定元素是否实际上在树中,如 XAML 中所示,只是没有绑定?如果不是,那也可以解释这样的错误。

Edit: I just noticed that your bindings might be a bit off, they do not translate to the XAML you posted as in the XAML you bind the Text and in your code you set the binding on the TagProperty. Ignoring that the binding should work in theory, just note that immediately after setting the bindig the value of the bound property will be null as mentioned earlier, so do not remove it right away (and bind the TextProperty if you want visual results).

于 2011-09-16T02:18:35.997 回答