你不需要这些。从概念上讲,TabControl 只是ObservableCollection<ViewModel> 的图形表示,其中每个视图模型由一个选项卡项表示,并且在给定时间只有 1 个SelectedItem:
<Window x:Class="WpfApplication4.Window12"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window12" Height="300" Width="300">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
</Window.Resources>
<TabControl ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
<Setter Property="Visibility" Value="{Binding IsVisible, Converter={StaticResource BoolToVisibilityConverter}}"/>
<Setter Property="Header" Value="{Binding Title}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
</Window>
代码背后:
using System.Windows;
using BaseFramework.MVVM;
using System.Collections.ObjectModel;
namespace WpfApplication4
{
public partial class Window12 : Window
{
public Window12()
{
InitializeComponent();
DataContext = new TabbedViewModel()
{
Items =
{
new TabViewModel() {Title = "Tab #1", IsEnabled = true, IsVisible = true},
new TabViewModel() {Title = "Tab #2", IsEnabled = false, IsVisible = true},
new TabViewModel() {Title = "Tab #3", IsEnabled = true, IsVisible = false},
}
};
}
}
视图模型:
public class TabbedViewModel: ViewModelBase
{
private ObservableCollection<TabViewModel> _items;
public ObservableCollection<TabViewModel> Items
{
get { return _items ?? (_items = new ObservableCollection<TabViewModel>()); }
}
private ViewModelBase _selectedItem;
public ViewModelBase SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
NotifyPropertyChange(() => SelectedItem);
}
}
}
public class TabViewModel: ViewModelBase
{
private string _title;
public string Title
{
get { return _title; }
set
{
_title = value;
NotifyPropertyChange(() => Title);
}
}
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set
{
_isEnabled = value;
NotifyPropertyChange(() => IsEnabled);
}
}
private bool _isVisible;
public bool IsVisible
{
get { return _isVisible; }
set
{
_isVisible = value;
NotifyPropertyChange(() => IsVisible);
}
}
}
}
然后,只需为您的每个选项卡继承TabViewModel(在每个选项卡内部创建适当的逻辑),并为app.xaml 中的每个派生类中的每一个适当的DataTemplate 或其他东西.
每当您想从视图中删除选项卡项时,您都可以操作 ViewModel,而不是操作视图。这是所有事情的 WPF 方法。它消除了在代码中操作复杂对象(UI 元素)的需要,从而简化了一切。每当你设置
TabbedViewModel.SelectedItem.IsVisible = false;,请确保您也这样做:
TabbedViewModel.SelectedItem = TabbedViewModel.Items.First(x => x.IsVisible && x.IsEnabled);
这将防止您陷入将不可见的选项卡项作为选定项的情况。