如何在WPF中使用关闭按钮关闭选项卡?

8

我正在开发一个WPF应用程序,当点击按钮时它会创建新的选项卡。这部分已经很好地实现了。但是我很难弄清如何在选项卡标题旁边添加一个关闭按钮,例如X,并关闭所选的选项卡?

MainWindow.xaml

<Grid>
        <StackPanel Name="listConnections" Grid.Column="0" Background="#4682b4" Margin="0,0,0,-0.2" >
        </StackPanel>            
        <TabControl Name="tabConnections" Grid.Column="1" TabStripPlacement="Top" Margin="0,0,0.4,-0.2">
        </TabControl>
    </Grid>
</Window>

为在按钮点击后创建新选项卡,需添加Tab方法 MainWindow.xaml.cs

public void addTab(Connection connection)
{
    TabItem tab = new TabItem();
    tab.Header = connection.name;
    tabConnections.Items.Add(tab);
}

有没有一种简单的方法来实现关闭按钮?

1
tabConnections.Items 的类型是什么?它有 Remove 方法吗? - Kfir Guy
1
是的,它可以。如果我创建一个closeTab方法,它能够关闭选定的标签吗?TabItem类有一个OnSelected方法,但我很难让X按钮显示在选项卡标题旁边。 - Truecolor
1
检查我的答案以获取关闭按钮和删除选项卡的说明和示例。 - Timon Post
2个回答

12

问题的答案:

  1. 创建选项卡。

    使用堆栈面板来将文本框和关闭图像水平对齐。请参考以下示例。

  2. 单击关闭按钮后删除选项卡。

    为了关闭选项卡,可以在代码中创建一个事件处理程序来处理单击事件。在此事件处理程序中,您可以简单地使用以下代码:

    tabConnections.Items.RemoveAt(tabConnections.SelectedIndex);
    
    我为什么要使用所选索引?因为当您单击选项卡时,该选项卡就变成了所选选项卡。在单击事件处理程序之后,可以删除与所选索引相等的索引的选项卡。

示例:

在此示例中,我为TabControl创建动态内容。通过使用自己的UserControls作为内容。此外,此示例将在选项卡中提供关闭图像。因此,首先创建一个Tab类和其后面的视图模式。

选项卡

// This class will be the Tab int the TabControl
public class ActionTabItem
{
    // This will be the text in the tab control
    public string Header { get; set; }
    // This will be the content of the tab control It is a UserControl whits you need to create manualy
    public UserControl Content { get; set; }
}

查看模态框

/// view model for the TabControl To bind on
public class ActionTabViewModal
{
    // These Are the tabs that will be bound to the TabControl 
    public ObservableCollection<ActionTabItem> Tabs { get; set; }

    public ActionTabViewModal()
    {
        Tabs = new ObservableCollection<ActionTabItem>();
    }

    public void Populate()
    {
        // Add A tab to TabControl With a specific header and Content(UserControl)
        Tabs.Add(new ActionTabItem { Header = "UserControl 1", Content = new TestUserControl() });
        // Add A tab to TabControl With a specific header and Content(UserControl)
        Tabs.Add(new ActionTabItem { Header = "UserControl 2", Content = new TestUserControl() });
    }
}

现在我们需要创建 XAML,将选项卡项与上面的 ViewModel 绑定。

  1. Action Tab item 中的 Header 绑定到 TabControl 中的 TextBlock 上

  2. 为图像控件指定来自关闭按钮图像的路径

  3. ContentAction Tab item 绑定到 UserControl 上

  4. 使用 StackPanel 进行标题信息和关闭图像的排列,并使其水平对齐。

    <Grid>
        <TabControl x:Name="actionTabs" DockPanel.Dock="Right" Background="White">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Height="21" Width="100">
                        <TextBlock Width="80" Text="{Binding Header}"/>
                        <Image Source="PathToFile\close.png" Width="20" Height="20" MouseDown="Image_MouseDown"/>
                    </StackPanel>
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <DataTemplate>
                    <UserControl Height="800" Width="1220" Content="{Binding Content}" Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>
    </Grid>

在代码后台

public partial class Window1 : Window
{
    private ActionTabViewModal vmd;

    public Window1()
    {
        InitializeComponent();
        // Initialize viewModel
        vmd  = new ActionTabViewModal();
        // Bind the xaml TabControl to view model tabs
        actionTabs.ItemsSource = vmd.Tabs;
        // Populate the view model tabs
        vmd.Populate();
    }

    private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    { 
        // This event will be thrown when on a close image clicked
        vmd.Tabs.RemoveAt(actionTabs.SelectedIndex);
    }
}

结果:


1
这个很好用,但我想在MVVM中使用命令绑定,但由于某种原因它没有触发我的命令。我只能让它在代码后台触发Click事件。 - Christopher Painter
1
对我来说,这个答案只有在使用MouseUp而不是MouseDown时才有效,因为否则按下按钮的选项卡尚未被选择。 - RealHackerLOL

2

这对我有用

  1. 创建带有用户控件的
<Grid >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Button Grid.Column="2" Content="X"  Height="19" Click="button_close_Click" HorizontalAlignment="Right" Margin="0,3,4,0" 
          VerticalAlignment="Top" Width="20" FontFamily="Courier" 
          FontWeight="Bold" 
          FontStretch="Normal"
          FontSize="14" Background="IndianRed"/>
        <Label Grid.ColumnSpan="2" Height="23" HorizontalAlignment="Left" 
          Margin="4,1,0,0" VerticalAlignment="Top" 
          FontFamily="Courier" FontSize="12" x:Name="NameLabel"/>
    </Grid>

2. 用户控件类

public partial class CloseHeader : UserControl
    {
        MainWindow _shell;
        int _index;
        public CloseHeader(MainWindow shell, int index, string headerName)
        {
            InitializeComponent();
            _shell = shell;
            _index = index;
            NameLabel.Content = headerName;
        }

        private void button_close_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            _shell.CloseTab(_index);
        }
    }
  1. 在主窗口中

    List<int> _tabs = new List<int>();
    int countIndex = 1;

    public void AddNewTab(HomeFunctions function)//HomeFunctions is an enum
    {
        int newIndex = countIndex++;
        _tabs.Add(newIndex);
        switch (function)
        {
            case HomeFunctions.Settings:
                tabControl.Items.Add(new TabItem { Content = new SettingsControl(this), Width = 100, Header = new CloseHeader(this, newIndex, HomeFunctions.Settings.ToString()) });
                break;
        }
        tabControl.SelectedIndex = newIndex;
    }

    public void CloseTab(int tabId)
    {
        tabControl.Items.RemoveAt(_tabs.IndexOf(tabId));//tabControl.Items.RemoveAt(_tabs.IndexOf(tabId) + 1); if you have a non closeable tab first like i do in mine
      _tabs.Remove(tabId);
    }


谢谢。这个实现比其他回答要容易一些。值得注意的是,在按钮上,没有“OnClick”。它只是“Click”。 - Ricky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接