我正在编写一些以编程方式动态创建绑定的代码,但我似乎无法读取将 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 绑定)但我很好奇为什么这不起作用。
提前致谢!