簡體   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