繁体   English   中英

以编程方式创建RelativeSource FindAncestor绑定

[英]Programmatically creating a RelativeSource FindAncestor binding

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

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

System.Windows.Data警告:64:BindingExpression(哈希= 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绑定),但我很好奇为什么这行不通。

提前致谢!

绑定属性后,您无法立即获得绑定属性的值,您当前正在使用处理程序操作来阻塞UI线程,绑定仅在线程空闲后才会进行(我认为)。

您应该删除Always null注释之后的所有内容,然后再检查该值,例如,在另一个按钮的处理程序中。 另外,绑定元素实际上是否在树中(如XAML所示)没有绑定? 如果没有,那也将解释这种错误。

编辑:我只是注意到您的绑定可能有点偏离,它们不会转换为您发布的XAML,因为您在绑定Text的XAML和您在代码中设置TagProperty的绑定。 忽略绑定在理论上应该起作用,只需注意设置bindig后,绑定属性的值将立即变为null,如前所述,因此不要立即将其删除(如果需要视觉效果,请绑定TextProperty )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM