如何在使用ItemsSource

时间:2017-02-09 11:06:10

标签: c# wpf xaml data-binding

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

1 个答案:

答案 0 :(得分:3)

您是否尝试设置项容器的附加属性?:

<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>
相关问题