I am writing some code which programmatically creates bindings on the fly, but I can't seem to read the value resulting from a binding whose RelativeSourceMode is set to FindAncestor. I was wondering if anybody has successfully created a RelativeSource binding in code (not XAML) with this mode?
With Binding tracing turned the warning is:
System.Windows.Data Warning: 64 : BindingExpression (hash=57957548): RelativeSource (FindAncestor) requires tree context
Here is sample code which creates the RelativeSource binding:
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;
}
And here is the corresponding 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>
The tree is loaded, so I could simulate the FindAncestor binding (using VisualTreeHelper.GetParent(...)
to locate the target element of the FindAncestor binding and then just apply a RelativeSource Self binding to it) but I'm curious as to why this doesn't work.
Thanks in advance!