问题
I have a MVVM desktop application. In my View, I have a TabControl
.
Any suggestions on the best practice to switch to a specific tab by changing a property on the ViewModel?
I suppose it could be done with a SelectedTab
property, but then the Tabs have to exist in the ViewModel, and the View must bind to the Tabs list in ViewModel. At the moment, the two tabs are static, in the sence that I won't be creating/deleting any dynamically during execution. So I create the tabs in the View, and they represent two different sets of control bound to the same ViewModel, so it's not a case of different tabs for different view model instances.
回答1:
Try binding to the SelectedIndex property to switch to a Tab.
回答2:
Not sure what MVVM framework you're using, but a possible solution is to have a ViewModel for each tab, with a parent ViewModel.
Then the parent ViewModel can activate the relevant child ViewModel, which will then activate the correct View.
回答3:
Create an IsSelected property on your viewmodel that you can databind to the tabitem's IsSelected property
回答4:
From MVVM
perspectives ViewModel should NOT be aware of View details like TabContainer
and so on, so for ViewModel it does not matter whether on underlying View used TabContainer
or ListView
control. So consider something straightforward like simple IEnumerable<IRepresentationItem> Items
to be exposed by ViewModel and then bound to UI items container of the underlying View.
And obviously expose SelectedItemIndex
property which could be bound to corresponding SelectedTab/SelectedItem Index of UI Items container.
来源:https://stackoverflow.com/questions/7305476/how-can-i-switch-tabs-programatically-from-within-my-viewmodel