我正在编写一些以编程方式动态创建绑定的代码,但我似乎无法读取其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自绑定),但我很好奇为什么这不起作用。
提前感谢!
发布于 2011-09-16 02:18:35
绑定后无法立即获得绑定属性的值,您目前正在用处理程序操作阻塞UI线程,绑定将只在线程空闲时发生(我认为)。
您应该删除Always null注释后的所有内容,并在以后检查该值,例如在另一个按钮的处理程序中。此外,绑定元素实际上是否如XAML中所示,没有绑定?否则,这也将解释这样的错误。
编辑:--我刚刚注意到,您的绑定可能有点错误,它们不会转换到您发布的XAML,比如在XAML中绑定Text,在代码中将绑定设置在TagProperty上。忽略绑定理论上的工作原理,只需注意在设置绑定之后,绑定属性的值将如前面提到的那样为null,所以不要立即删除它(如果您想要可视化的结果,请绑定TextProperty )。
https://stackoverflow.com/questions/7439471
复制相似问题