C# 将命令与TabItem一起使用

C# 将命令与TabItem一起使用,c#,wpf,mvvm,command,C#,Wpf,Mvvm,Command,我想在选择TabControl的TabItem时调用命令 有没有一种方法可以在不破坏MVVM模式的情况下执行此操作?使用,它将允许您将命令绑定到WPF事件 <TabControl ... local:CommandBehavior.Event="SelectionChanged" local:CommandBehavior.Command="{Binding TabChangedCommand}" /> 可以同时使用以下类完成此操作: EventTrigger

我想在选择TabControl的TabItem时调用命令

有没有一种方法可以在不破坏MVVM模式的情况下执行此操作?

使用,它将允许您将命令绑定到WPF事件

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

可以同时使用以下类完成此操作:

  • EventTrigger
    来自
    System.Windows.Interactivity
    命名空间(
    System.Windows.Interactivity
    assembly)的类
  • EventToCommand
    来自
    GalaSoft.MvvmLight.Command
    命名空间的类(例如,程序集
    GalaSoft.MvvmLight.Extras.WPF4
    ):
XAML:


您还可以绑定到IsSelected并在ViewModel中处理对该属性的更改。这只是从中获得的交互性,您不需要任何MVVM框架来使用它。@H.B.,这对于
EventTrigger
类是正确的。但是
EventToCommand
类属于MVVM Light工具包。
void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    if (e.PropertyName == "SelectedIndex")
        RunTabChangedLogic();
}
<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>
TabSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(args =>
    {
        // Command action.
    });