WPF 根据按钮增加TabItem每一个TabItem的标题右上角都有一个删除小小的X代表可以删除这个选项卡完整代码
XAML代码:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Tab Item Demo" Height="350" Width="500">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Content="Add Tab" Click="AddTab_Click" Margin="10"/>
<TabControl Grid.Row="1" x:Name="tabControl" SelectionChanged="TabControl_SelectionChanged">
<TabControl.Resources>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<ContentPresenter ContentSource="Header"/>
<Button x:Name="closeButton" Content="X" Margin="5,0,0,0" Click="CloseButton_Click"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="closeButton" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="closeButton" Property="Visibility" Value="Collapsed"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
</TabControl>
</Grid>
</Window>
C#代码:
using System.Windows;
using System.Windows.Controls;
namespace WpfApp1
{
public partial class MainWindow : Window
{
private int tabCount = 0;
public MainWindow()
{
InitializeComponent();
}
private void AddTab_Click(object sender, RoutedEventArgs e)
{
tabCount++;
TabItem tabItem = new TabItem();
tabItem.Header = "Tab " + tabCount;
tabControl.Items.Add(tabItem);
tabControl.SelectedItem = tabItem;
}
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Button closeButton = sender as Button;
TabItem tabItem = closeButton.Parent as TabItem;
tabControl.Items.Remove(tabItem);
}
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (TabItem tabItem in tabControl.Items)
{
if (tabItem != tabControl.SelectedItem)
{
tabItem.IsSelected = false;
}
}
}
}
}
``
原文地址: https://www.cveoy.top/t/topic/cvV5 著作权归作者所有。请勿转载和采集!