wpfbindingrelativesource

Binding Context by Relative Source


I would like to bind my DataTemplate (ClosableTabItemTemplate) to the Workspaces DataContext of the HeaderedContentControl by Relative Source. Unfortunately it doesn't work? Any ideas?

Btw: I get the following command line error: System.Windows.Data Error: 40 : BindingExpression path error: 'DisplayName' property not found on 'object' ''AllUserView' (Name='')'. BindingExpression:Path=DataContext.DisplayName; DataItem='TabItem' (Name=''); target element is 'ContentPresenter' (Name=''); target property is 'Content' (type 'Object')

Cya Michael

<HeaderedContentControl 
      Content="{Binding Path=Workspaces}"
      ContentTemplate="{StaticResource WorkspacesTemplate}"
      Header=""
      Style="{StaticResource MainHCCStyle}" DataContext="{Binding}" 
                />
<DataTemplate x:Key="ClosableTabItemTemplate">
    <DockPanel Width="120"  >
        <Button 
    Command="{Binding Path=DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType={x:Type HeaderedContentControl}}}"
    Content="X"
    Cursor="Hand"
    DockPanel.Dock="Right"
    Focusable="False"
    FontFamily="Courier" 
    FontSize="9"
    FontWeight="Bold"  
    Margin="0,1,0,0"
    Padding="0"
    VerticalContentAlignment="Bottom"
    Width="16" Height="16" 
    />
    <ContentPresenter 
    Content="{Binding Path=DataContext.DisplayName, RelativeSource={RelativeSource AncestorType={x:Type HeaderedContentControl}}}" 
    VerticalAlignment="Center" 
    />
    </DockPanel>
</DataTemplate>

<DataTemplate x:Key="WorkspacesTemplate">
    <TabControl 
  IsSynchronizedWithCurrentItem="True" 
  ItemsSource="{Binding}"      
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4"
  />
</DataTemplate>

Solution

  • I think you have to use RelativeSource.AncestorLevel Property. Default level is 1 and your WorkspacesTemplate TabControl is a HeaderedContentControl too. Try

    Content="{Binding Path=DataContext.DisplayName,
                      RelativeSource={RelativeSource AncestorType={x:Type HeaderedContentControl},
                                                     AncestorLevel=2}}" 
    

    to find your real HeaderedContentControl.