【问题标题】:Use a Command with TabItem对 TabItem 使用命令
【发布时间】:2012-03-15 04:58:54
【问题描述】:

当我的 TabControl 的 TabItem 被选中时,我想调用一个命令。

有没有办法在不破坏 MVVM 模式的情况下做到这一点?

【问题讨论】:

  • 您还可以绑定到 IsSelected 并在 ViewModel 中处理对该属性的更改。

标签: c# wpf mvvm command


【解决方案1】:

使用AttachedCommand Behavior,它将让您将命令绑定到 WPF 事件

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

当然,如果您使用 MVVM 设计模式并绑定 SelectedItemSelectedIndex,您也可以在 PropertyChanged 事件中运行命令

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

【讨论】:

    【解决方案2】:

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

    • EventTrigger 类来自 System.Windows.Interactivity 命名空间(System.Windows.Interactivity 程序集)。
    • 来自GalaSoft.MvvmLight.Command 命名空间的EventToCommand 类(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>
    

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

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

    【讨论】:

    • 这只是Blend SDK中的Interactivity,你不需要任何MVVM框架来使用它。
    • @H.B.,对于 EventTrigger 类是正确的。但是EventToCommand 类属于 MVVM Light Toolkit。
    猜你喜欢
    • 2012-11-17
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多