WPF 如何为当前活动的 tabitem 执行命令?

WPF How to execute command for current active tabitem?

我在 shell 视图中使用棱镜 TabControl Region

每个 TabItem 包含 AViewAViewModel

我可以在 AViewModel.

中使用 属性 IsActive 属性 来确定当前活动的 TabItem

IsActive 属性 仅针对当前选定的 TabItem 设置为 true

我在 Shell 视图中有一个按钮,它负责为 TabItems.

中的视图执行逻辑

根据当前激活的TabItem(设置可以执行commandtruefalse),只为活动视图执行逻辑。来自其他视图中的按钮?

我已经成功地通过创建composite command来执行command,然后将AViewModel的命令注册到composite command,并绑定里面的按钮shellcomposite command.

这种方法的问题是,如果任何命令 return false 除了一个 (活动的 TabItem), none 执行的命令。

The CompositeCommand class maintains a list of child commands (DelegateCommand instances). The Execute method of the CompositeCommand class simply calls the Execute method on each of the child commands in turn. The CanExecute method similarly calls the CanExecute method of each child command, but if any of the child commands cannot be executed, the CanExecute method will return false. In other words, by default, a CompositeCommand can only be executed when all the child commands can be executed. Source

创建选项卡的视图模型和 shell 的视图模型都知道的服务。当一个选项卡视图模型被激活时,它会向服务宣布自己。 shell 视图模型查看命令的服务(谁又转发到活动选项卡视图模型),或者(首选)服务托管命令并仅使用选项卡视图模型提供的信息.

CompositeCommand 显然是错误的命令,因为它设计用于在多个目标上执行,而您只希望它在单个目标(活动视图模型)上执行。

没有看到代码或 XAML,很难给出建议,但假设 XAML 看起来像这样:

<Grid>
 <Grid.RowDefinitions>
  <RowDefiniton Height="Auto" />
  <RowDefinition />
 </Grid.RowDefinitions>

 <Button Grid.Row="0" Content="Execute on Active" />
 <TabControl Grid.Row="1" ItemSource="{Binding TabViewModels}" prism:RegionManager.RegionName="TabRegion" IsSynchronizedWithCurrentItem="True" />

<Grid>

那么在活动项目上执行命令的最简单方法是使用“/”语法将 Button 上的命令 属性 设置为活动视图模型的 TargetCommand,它表示当前项目。

<Button Grid.Row="0" Content="Execute on Active" Command="{Binding TabViewModels/TargetCommand}" />

如果您使用的是 CompositeCommand,并且只想调用活动选项卡上的命令,则让您的 ViewModel 实现 IActiveAware。然后在 CompositeCommand 的构造函数中,将 true 作为参数传递。然后这将仅监视活动选项卡。