6

I would like to call a Command when a TabItem of my TabControl is selected.

Is there a way to do it without breaking the MVVM pattern ?

Peekyou
  • 471
  • 1
  • 5
  • 21
  • 1
    You can also bind to IsSelected and handle changes to that property in your ViewModel. –  Feb 24 '12 at 19:08

2 Answers2

7

Use an AttachedCommand Behavior, which will let you bind a Command to WPF events

<TabControl ...
    local:CommandBehavior.Event="SelectionChanged"  
    local:CommandBehavior.Command="{Binding TabChangedCommand}" />

Of course, if you're using the MVVM design pattern and binding SelectedItem or SelectedIndex, you could also run the command in the PropertyChanged event

void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "SelectedIndex")
        RunTabChangedLogic();
}
Rachel
  • 130,264
  • 66
  • 304
  • 490
5

It can be done using the following classes together:

  • EventTrigger class from the System.Windows.Interactivity namespace (System.Windows.Interactivity assembly).
  • EventToCommand class from the GalaSoft.MvvmLight.Command namespace (MVVM Light Toolkit assembly, for example, GalaSoft.MvvmLight.Extras.WPF4):

XAML:

<Window ...
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command
        ...>
...
    <TabControl>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="SelectionChanged">
                <cmd:EventToCommand Command="{Binding TabSelectionChangedCommand}"
                                    PassEventArgsToCommand="True" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <TabItem>...</TabItem>
        <TabItem>...</TabItem>
    </TabControl>
...
</Window>

Create an instance of the command in the ViewModel constructor:

TabSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(args =>
    {
        // Command action.
    });
  • 2
    That's just `Interactivity` from the [Blend SDK](http://www.microsoft.com/download/en/details.aspx?id=10801), you don't need any MVVM framework to use this. – H.B. Feb 24 '12 at 21:24
  • @H.B., it is correct for the `EventTrigger` class. But the `EventToCommand` class belongs to the MVVM Light Toolkit. – Sergey Vyacheslavovich Brunov May 13 '15 at 11:56