簡體   English   中英

使用ItemsSource時如何設置TabItem CommandBindings

[英]How to set TabItem CommandBindings when using ItemsSource

我在TabControl提供了一些工作區。 每個工作區都有一些綁定到某些ApplicationCommands命令綁定,例如

  • 新(Foo)
  • 保存(欄)
  • 收盤(Foo,Bar)

通過使用這些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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM