Search code examples
wpfmvvmprismtabcontroldelegatecommand

WPF How to execute command for current active tabitem?


I'm using prism TabControl Region inside the shell view.

Each TabItem contains AView and AViewModel.

I can determine the currently active TabItem using a property IsActive property in AViewModel.

IsActive property is set to true only for the current selected TabItem.

I have button inside the Shell view, which is responsible for executing logic for the views inside the TabItems.

What's the right way to enable disable the button according the current active TabItem(set can execute command to true or false), and execute the logic only for the active view. from a button placed in other view?

I have managed to execute the command by creating composite command, and then register the commands from the AViewModel to the composite command, and bind the button inside the shell to the composite command.

The problem with this approach, that if any of the commands return false which they're all except one (the active TabItem), none of the commands executed.

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


Solution

  • If you are using a CompositeCommand, and only want to invoke the command on the active Tab, then have your ViewModels implement IActiveAware. Then in the ctor of your CompositeCommand, pass true as the parameter. This will then monitor only the active tab.