【发布时间】:2018-03-23 18:50:42
【问题描述】:
我有一个带有TabControl 的主窗口。每个选项卡都包含一个与之关联的UserControl。在我的UserControl 之一中,我有一个按钮。当我单击按钮时,我想更改主窗口中的TabControl 的SelectedIndex。
我正在使用 MVVM 模式,所以如果可能的话,我想在 XAML 中使用按钮上的 Command 属性来实现。
例如:
<Button Content="Switch Tab" Command="SwitchTabCommand" />
提前感谢我的程序员伙伴!
编辑:
窗口视图模型:
public class CoolViewModel : BaseViewModel
{
#region Properties
public ObservableCollection<ITabViewModel> Tabs { get; set; }
public ITabViewModel SelectedTab { get; set; }
#endregion
#region Constructor
public CoolViewModel()
{
Tabs = new ObservableCollection<ITabViewModel>
{
new VeryNiceViewModel(),
new VeryNiceViewModel()
};
}
#endregion
}
这是标签内的 UserControl 的代码:
public class VeryCoolViewModel : BaseViewModel, ITabViewModel
{
#region Properties
public ObservableCollection<Test> Tests { get; set; }
public Test currentSelection { get; set; }
public string TabHeader { get; set; }
#endregion
#region Commands
ICommand GoToOtherTab { get; set; }
#endregion
#region Constructor
public GabaritSelecteurViewModel()
{
Tests = new ObservableCollection<Test>
{
new Test { Title = "Title #1" },
new Test { Title = "Title #2" },
new Test { Title = "Title #3" },
new Test { Title = "Title #4" },
new Test { Title = "Title #5" }
};
TabHeader = "Tests";
GoToOtherTab = new RelayCommand(GoToTab, parameter => true);
}
#endregion
#region Methods
private void GoToTab(object parameter)
{
// I don't know how to tell to the
// parent window to go to the other tab...
}
#endregion
}
这是 UserControl 的 XAML(位于 TabControl 内):
<Button Content="Go to the other tab" Command="{Binding GoToOtherTab}" />
【问题讨论】:
-
SelectedIndex 是一个 PITA。使用 SelectedItem 总是更容易(只要您的实例是 ItemsSource 集合中的一个)