WPF TabControl 使用命令更改 TabItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13621355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:24:44  来源:igfitidea点击:

WPF TabControl change TabItem with Command

wpfmvvmcommand

提问by Peter

I have a WPF application and in the main window I have a TabControl. I would like the TabItemsto fire a RelayCommandthat I have in my ViewModelwhen they get selected (different commands for each TabItem). I don't want a TabItemto be selected for some conditions that are set in the commands CanExecutefunction. Is this possible?

我有一个 WPF 应用程序,在主窗口中有一个TabControl. 我想在他们被选中时TabItems触发RelayCommand我的一个ViewModel(每个命令都有不同的命令TabItem)。我不希望TabItem为命令CanExecute函数中设置的某些条件选择a 。这可能吗?

回答by Jobi Joy

I think the right way to go here is not 'ICommand' but just a ViewModel property which will twoway bind to the TabControl.SelectedIndex (or SelectedItem) then you can take the decision in the ViewModel. This is better than defining a lot of commands specific to each TabItem

我认为正确的方法不是“ICommand”,而只是一个 ViewModel 属性,它将双向绑定到 TabControl.SelectedIndex(或 SelectedItem),然后您可以在 ViewModel 中做出决定。这比定义许多特定于每个 TabItem 的命令要好

<TabControl SelectedIndex="{Binding VMSelectedTabIndex, Mode=TwoWay}">
//OR
<TabControl SelectedItem="{Binding VMSelectedItem, Mode=TwoWay}">