我在页面上有一个标签控件;它的项目绑定回我的ViewModel,这个ViewModel还公开了ActiveTabItemIndex,该属性与我的xaml中SelectedIndex属性进行双向绑定,并实现了INotifyPropertyChanged接口,以便我的TabControl知道何时更新。
这是(据我所知)MVVM正确的做法,工作99%正确。
class MainWindowViewModel : BaseViewModel, INotifyPropertyChanged
{
ObservableCollection<TabItemViewModel> _TabItems;
int _ActiveTabItemIndex;
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
void _TabItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
_ActiveTabItemIndex = _TabItems.IndexOf((TabItemViewModel)e.NewItems[0]);
RaisePropertyChanged("ActiveTabItemIndex");
}
public ObservableCollection<TabItemViewModel> TabItems
{
get
{
if (_TabItems == null)
{
_TabItems = new ObservableCollection<TabItemViewModel>();
_TabItems.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_TabItems_CollectionChanged);
}
return _TabItems;
}
}
public int ActiveTabItemIndex
{
get
{
return _ActiveTabItemIndex;
}
set
{
_ActiveTabItemIndex = value;
}
}
}
这样,我对TabItems集合进行的任何操作都会反映在TabControl上,当我添加新项时,它会自动选择。这个方法非常有效; 然而,当向空选项卡控件添加第一个项目时,它看起来像这样:
![Tab contents displayed but tab not selected](https://istack.dev59.com/KGXOk.webp)
![Tab contents displayed and tab selected](https://istack.dev59.com/Ta5GJ.webp)