我想在选择TabControl的TabItem时调用Command。
有没有办法在不破坏MVVM模式的情况下做到这一点?
答案 0 :(得分:6)
使用AttachedCommand Behavior,可以将Command绑定到WPF事件
<TabControl ...
local:CommandBehavior.Event="SelectionChanged"
local:CommandBehavior.Command="{Binding TabChangedCommand}" />
当然,如果您正在使用MVVM设计模式并绑定SelectedItem
或SelectedIndex
,您还可以在PropertyChanged
事件中运行该命令
void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SelectedIndex")
RunTabChangedLogic();
}
答案 1 :(得分:5)
可以一起使用以下类来完成:
EventTrigger
命名空间(System.Windows.Interactivity
程序集)的System.Windows.Interactivity
类。EventToCommand
命名空间(MVVM Light Toolkit程序集的GalaSoft.MvvmLight.Command
类,例如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.
});
答案 2 :(得分:0)
这是我在没有GalaSoft.MvvmLight
或Attached Command Behavior的情况下所做的事情
<TabControl Name="MyTabControl">
<TabItem x:Name="FirstDataGridTab">
<TabItem.InputBindings>
<MouseBinding Command="{Binding MyCommand}" MouseAction="LeftClick" />
</TabItem.InputBindings>
...
</TabControl>
// In my ViewModel
public ICommand MyCommand
{
get
{
return new RelayCommand((object parameters) =>
{
// Do stuff...
});
}
}