2012-02-24 11 views
5

Me gustaría llamar a un comando cuando se selecciona un TabItem de mi TabControl.Usar un comando con TabItem

¿Hay alguna manera de hacerlo sin romper el patrón MVVM?

+1

También puede enlazar a IsSelected y gestionar los cambios en esa propiedad i n su ViewModel. – Will

Respuesta

6

Utilice un AttachedCommand Behavior, que le permitirá enlazar un comando de eventos de WPF

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

Por supuesto, si usted está utilizando el patrón de diseño MVVM y vinculante SelectedItem o SelectedIndex, que también podría ejecutar el comando de el evento PropertyChanged

void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    if (e.PropertyName == "SelectedIndex") 
     RunTabChangedLogic(); 
} 
5

se puede hacer uso de las siguientes clases juntos:

  • EventTrigger clase del espacio de nombres System.Windows.Interactivity (ensamblaje System.Windows.Interactivity).
  • EventToCommand clase desde el GalaSoft.MvvmLight.Command espacio de nombres (MVVM Light Toolkit montaje, por ejemplo, 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> 

crear una instancia de la orden en el ViewModel constructor:

TabSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(args => 
    { 
     // Command action. 
    }); 
+1

Eso es solo 'Interactividad' del [Blend SDK] (http://www.microsoft.com/download/en/details.aspx?id=10801), no necesita ningún framework MVVM para usar esto. –

+0

@ H.B., Es correcto para la clase 'EventTrigger'. Pero la clase 'EventToCommand' pertenece a MVVM Light Toolkit. –

+0

Pregunta relacionada: http://stackoverflow.com/q/5868589/490018. –

Cuestiones relacionadas