好吧,让我们来看看:
首先,你必须学会以一种abstract way:
什么是 TabControl?
它是小部件列表的图形表示,其中用户一次可以拥有 1 个活动小部件。这些小部件具有标题(选项卡项文本)、可见性状态和启用/禁用状态。
什么是一堆堆叠按钮? (工具栏,如果你想这样称呼它)
它是用户可以在任何给定时间执行的操作列表的图形表示。这些操作有一个描述(按钮的内容),可能有一个关联的图标或图形图像,以及一个启用/禁用状态。
什么是上下文菜单或菜单?
与上面相同,它是用户可以执行的操作列表的图形表示。
我将如何在 WPF 中创建动态 TabControl?
这是支持动态子项的 WPF TabControl 的 XAML:
<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>
视图模型:
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);
}
}
}
在此示例中,TabControl 中的每个项目 (TabItem) 将绑定到其中一个 ViewModel,那么只需为每个选项卡继承基本 TabViewModel 并创建一个适当的 ViewModel 即可。DataTemplate
对于每个。
正如您在此示例中所看到的,我绝不会在代码中创建或操作任何 UI 元素。这大大简化了所有代码,并有助于保持逻辑和 UI 之间的清晰分离。
您可以将相同的概念应用于 WPF 中的所有内容。