user3230660
user3230660

Reputation:

RelativeSource binding does not work

The first textbox below cannot find the parent TabItem however the second textbox can. What am I doing wrong in the first binding?

<TabItem Style="{StaticResource TabItemStyle}" x:Name="zzzzz">
   <StackPanel >
      <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TabItem}}, Path=IsSelected}"></TextBlock>
      <TextBlock Text="{Binding ElementName=zzzzz, Path=IsSelected}" />
   </StackPanel>
</TabItem>

The error message is: System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.TabItem', AncestorLevel='1''. BindingExpression:Path=IsSelected; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')

I've never had to set AncestorLevel but I tried setting it to 5000 it still does not work.

Note that I am not setting the binding from the DataTemplate as is shown in this question.

Upvotes: 0

Views: 902

Answers (1)

mm8
mm8

Reputation: 169160

The TabItem is not a visual ancestor of the TextBlock in the content panel of the TabControl so your first binding won't ever work.

If you put a TextBlock in the header of a TabItem, you can bind to the latter using a {RelativeSource}. But the currently visible content panel is a visual child of the TabContol itself rather than a specific TabItem.

Upvotes: 0

Related Questions