我有TabControl的在其上我设置文本菜单。

所有文本菜单元件已经命令用于设置。

<ContextMenu x:Key="tabMenu">
  <MenuItem Command="{x:Static tabs:TabCommands.Close}" />
  <MenuItem Command="{x:Static tabs:TabCommands.CloseAllButThis}" />
  <MenuItem Command="{x:Static tabs:TabCommands.CloseAll}" />
</ContextMenu>

所有的命令被路由,并且化CommandBindings的定义与上述的TabControl几个级别。

所以现在的问题是:在CanExecute的CommandBinding /执行事件处理程序,什么是要找出哪个TabItem的菜单被调用的正确方法?通过正确的我的意思是,如果我改变的东西像TabItem的模板,不会打破的。

或者可以是整个的做法是错误的,我不应该使用路由命令为这个?我已经最初使用的路由添加新选项卡命令需要热键。

预先感谢。

<强>更新

伊戈尔的解决方案是从建筑POV清洁剂(除了我会删除_在视图模型),但我希望有一个可重复使用的关闭命令是独立于什么TabControl的必然(因为关闭/关闭所有标签存在于所有种应用程序,而不是语义上链接到特定的模型)。

另外,我无法使用自定义的DataTemplate因为我已经有一个自定义模板,并继承它将使解决方案过于复杂一点。

有帮助吗?

解决方案

看来我已经找到了自己的答案,但它是非常unelegant:

<Style TargetType="MenuItem">
  <Setter Property="CommandTarget">
    <Setter.Value>
      <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}"
               Path="(ContextMenu.PlacementTarget)" />
    </Setter.Value>
  </Setter>
</Style>

<Style TargetType="TabItem">
  <Setter Property="ContextMenu" Value="{StaticResource tabMenu}" />
</Style>

因此,我添加文本菜单到的TabItem代替TabControl的,并结合CommandTarget到的TabItem。

有趣的是,是否有更好的答案。

其他提示

当然,也有更好的答案。你需要使用模型/视图模型,无法查看工作。这里从我的代码的简化〔实施例:

        <TabControl Margin="3" Grid.Column="1" Name="tbPages"
                    ItemsSource="{Binding DsmProject.Pages}" 
                    ItemTemplate="{DynamicResource TabItemTemplate}"
                    IsSynchronizedWithCurrentItem="True">
        </TabControl>
<DataTemplate x:Key="TabItemTemplate">
    <StackPanel Orientation="Horizontal" ContextMenu="{DynamicResource cmPages}">
        <ContentPresenter Content="{Binding Path=Name}"/>
    </StackPanel>
</DataTemplate>
<ContextMenu x:Key="cmPages">
    <MenuItem Header="Close" Command="cmd:DSM2100Commands.ClosePage" CommandParameter="{Binding}" />
</ContextMenu>

下面是代码,它处理该命令。

区域 “关闭页面”

    Private Sub ClosePageCmd(ByVal sender As Object, ByVal e As ExecutedRoutedEventArgs)
        ViewModel_.History.TakeCommmand(New cmdRemovePage(ViewModel_, e.Parameter))
    End Sub

    Private Sub CanClosePageCmd(ByVal sender As Object, ByVal e As CanExecuteRoutedEventArgs)
        e.CanExecute = ViewModel_.DsmProject IsNot Nothing AndAlso ViewModel_.DsmProject.Pages.Count > 1
    End Sub

的端部区域

正如你所看到的,我的代码没有必要知道的TabItem被点击,只需要知道哪些数据对象被绑定到这个TabItem的。无论如何,如果你需要知道的TabItem,它被点击,你可以找到它通过数据对象使用ContainerGenerator对象和你的DataTemplate界吧。

使用来自俄罗斯的祝福!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top