2017-02-09 22 views
1

我在TabControl中提供了一些工作區。每個workpace有綁定到其他ApplicationCommands如何在使用ItemsSource時設置TabItem CommandBindings

  • 新(美孚)一些命令綁定
  • 保存(酒吧)
  • 關閉(美孚,酒吧)

菜單是建立通過使用這些ApplicationCommands

<Menu> 
    <MenuItem Command="ApplicationCommands.New"/> 
    <MenuItem Command="ApplicationCommands.Save"/> 
    <MenuItem Command="ApplicationCommands.Close"/> 
</Menu> 

這是版本Ÿ易用當TabControl手動有線

<TabControl> 
    <TabControl.Resources> 
     <Style TargetType="TabItem"> 
      <Setter Property="HeaderTemplate" Value="{StaticResource ClosableTabItemTemplate}"/> 
     </Style> 
    </TabControl.Resources> 
    <TabItem DataContext="{Binding Foo}" 
      Header="{Binding}" 
      Content="{Binding}" 
      local:AttachedProperties.RegisterCommandBindings="{Binding Path=CommandBindings}"/> 
    <TabItem DataContext="{Binding Bar}" 
      Header="{Binding}" 
      Content="{Binding}" 
      local:AttachedProperties.RegisterCommandBindings="{Binding Path=CommandBindings}"/> 
</TabControl> 

這個命令當我只選擇我TabItem可以使用菜單來執行這些命令。

但工作區不是靜態的,所以我必須綁定到工作區的集合。現在,它是不夠的,選擇TabItem,我也只好激活內容,從菜單中使用的命令(不suprising,因爲TabItem是活動沒有任何命令綁定)

<TabControl ItemsSource="{Binding Path=Workspaces}"> 
    <TabControl.Resources> 
     <Style TargetType="TabItem"> 
      <Setter Property="HeaderTemplate" Value="{StaticResource ClosableTabItemTemplate}"/> 
     </Style> 
    </TabControl.Resources> 
</TabControl> 

這裏DataTemplate中爲TabItem

<DataTemplate x:Key="ClosableTabItemTemplate"> 
    <DockPanel LastChildFill="True"> 
     <Button Content="X" DockPanel.Dock="Right" Command="{Binding Path=CloseCommand}"/> 
     <TextBlock Text="{Binding Path=DisplayName}"/> 
    </DockPanel> 
</DataTemplate> 

如何設置化CommandBindings到動態創建TabItem或如何得到的TabItem本身使用我的AttachedProperties.RegisterCommandBindings

更新

作爲一種變通方法(也許這是唯一可能的解決方案)我的命令綁定到TabControl本身

<TabControl ItemsSource="{Binding Path=Workspaces}" 
      local:AttachedProperties.RegisterCommandBindings="{Binding RelativeSource={RelativeSource Self},Path=SelectedItem.CommandBindings}"> 
    <TabControl.Resources> 
     <Style TargetType="TabItem"> 
      <Setter Property="HeaderTemplate" Value="{StaticResource ClosableTabItemTemplate}"/> 
     </Style> 
    </TabControl.Resources> 
</TabControl> 

回答

2

你有沒有嘗試設置的附加屬性物品容器?:

<TabControl ItemsSource="{Binding Path=Workspaces}"> 
    <TabControl.ItemContainerStyle> 
     <Style TargetType="TabItem"> 
      <Setter Property="local:AttachedProperties.RegisterCommandBindings" Value="{Binding RelativeSource={RelativeSource Self}, Path=CommandBindings}" /> 
      <Setter Property="HeaderTemplate" Value="{StaticResource ClosableTabItemTemplate}"/> 
     </Style> 
    </TabControl.ItemContainerStyle> 
</TabControl> 
+0

這是我一直在尋找的 - 所有豎起大拇指 –

相關問題