相对来源绑定上下文

时间:2012-07-21 16:41:17

标签: wpf binding relative

我想将DataTemplate(ClosableTabItemTemplate)绑定到Relative Source的HeaderedContentControl的Workspaces DataContext。不幸的是它不起作用?有什么想法吗?

顺便说一下: 我收到以下命令行错误: System.Windows.Data错误:40:BindingExpression路径错误:'object'上找不到'DisplayName'属性'''AllUserView'(Name ='')'。 BindingExpression:路径= DataContext.DisplayName; DataItem ='TabItem'(Name =''); target元素是'ContentPresenter'(Name =''); target属性是'Content'(类型'Object')

氰 迈克尔

<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>

1 个答案:

答案 0 :(得分:0)

我认为你必须使用RelativeSource.AncestorLevel Property。默认级别为1,您的WorkspacesTemplate TabControl也是HeaderedContentControl。尝试

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

找到真正的HeaderedContentControl