【问题标题】:Binding Context by Relative Source通过相对源绑定上下文
【发布时间】:2012-07-21 16:41:16
【问题描述】:

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

顺便说一句: 我收到以下命令行错误: System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“AllUserView”(名称=“”)上找不到“DisplayName”属性。 BindingExpression:Path=DataContext.DisplayName; DataItem='TabItem' (名称='');目标元素是'ContentPresenter'(名称='');目标属性是“内容”(类型“对象”)

Cya 迈克尔

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

【问题讨论】:

  • 我认为在数据模板中你也必须使用 FindAncestor
  • ContentPresenters 实际上是专门用于 ControlTemplates,而不是 DataTemplates。考虑使用 TextBlock 并绑定到 Text 属性。命令绑定成功了吗?

标签: wpf binding relativesource


【解决方案1】:

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

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

找到你真正的HeaderedContentControl

【讨论】:

  • 感谢您的回答。但是,如果我添加 AncestorLevel,则使用 MainWindow 的 DataContext。
  • 而你的 AllUserView 是什么?它在您的 VisualTree 中的什么位置?
  • AllUserView 是正确的视图。但 Command 和属性是 AllUserViewModel 的一部分。
  • 解决方案是将路径设置为 DataContext.DataContext... 在我写最后一条评论时,我明白了 :-) THX
猜你喜欢
  • 2018-09-05
  • 2018-11-27
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多