使用带TabItem的命令

Pee*_*you 5 c# wpf command mvvm

当我的TabControl的TabItem被选中时,我想调用一个Command.

有没有办法在不破坏MVVM模式的情况下完成它?

Rac*_*hel 7

使用AttachedCommand Behavior,它允许您将Command绑定到WPF事件

<TabControl ...
    local:CommandBehavior.Event="SelectionChanged"  
    local:CommandBehavior.Command="{Binding TabChangedCommand}" />
Run Code Online (Sandbox Code Playgroud)

当然,如果您正在使用MVVM设计模式和绑定,SelectedItem或者SelectedIndex您也可以在PropertyChanged事件中运行该命令

void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "SelectedIndex")
        RunTabChangedLogic();
}
Run Code Online (Sandbox Code Playgroud)


Ser*_*nov 5

可以一起使用以下类来完成:

  • EventTrigger类从System.Windows.Interactivity命名空间(System.Windows.Interactivity组件).
  • EventToCommandGalaSoft.MvvmLight.Command命名空间中的类(例如,MVVM Light Toolkit程序集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>
Run Code Online (Sandbox Code Playgroud)

ViewModel构造函数中创建命令的实例:

TabSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(args =>
    {
        // Command action.
    });
Run Code Online (Sandbox Code Playgroud)

  • 这只是 [Blend SDK](http://www.microsoft.com/download/en/details.aspx?id=10801) 中的“交互性”,您不需要任何 MVVM 框架来使用它。 (2认同)