[英]How to set TabItem CommandBindings when using ItemsSource
我在TabControl
提供了一些工作區。 每個工作區都有一些綁定到某些ApplicationCommands
命令綁定,例如
通過使用這些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
還不夠,我還必須激活內容,才能使用菜單中的命令(不必驚訝,因為TabItem
是活動的,沒有任何命令綁定)
<TabControl ItemsSource="{Binding Path=Workspaces}">
<TabControl.Resources>
<Style TargetType="TabItem">
<Setter Property="HeaderTemplate" Value="{StaticResource ClosableTabItemTemplate}"/>
</Style>
</TabControl.Resources>
</TabControl>
這是TabItem
的DataTemplate
<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>
您是否嘗試設置了項目容器的附加屬性?:
<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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.