- 1 year ago
I can't delete a TabView tab when it is selected in WinUI 3
In WinUI 3, you cannot delete a TabViewItem
that is currently selected in a TabView
control. This is because the TabView
control requires at least one tab to be visible at all times.
To delete a TabViewItem
that is currently selected, you must first select another tab. Here's an example of how you can do this:
- Get the currently selected
TabViewItem
:
csharpTabViewItem selectedTab = myTabView.SelectedItem as TabViewItem;
- Create an event handler for the
TabView.TabCloseRequested
event:
csharpmyTabView.TabCloseRequested += MyTabView_TabCloseRequested;
- In the event handler, check if the
TabViewItem
being closed is the currently selected tab. If it is, select another tab before removing the selected tab:
csharpprivate void MyTabView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
{
if (args.Tab == myTabView.SelectedItem)
{
// Select another tab
int selectedIndex = myTabView.TabItems.IndexOf(args.Tab);
myTabView.SelectedIndex = selectedIndex == 0 ? 1 : selectedIndex - 1;
}
// Remove the tab
myTabView.TabItems.Remove(args.Tab);
}
In this example, the TabView.TabCloseRequested
event is handled by the MyTabView_TabCloseRequested
method. The method first checks if the TabViewItem
being closed is the currently selected tab. If it is, the method selects another tab before removing the selected tab. The selected index is calculated using the IndexOf
method of the TabItems
collection, and the SelectedIndex
property is set to the new index. Finally, the TabViewItem
is removed from the TabItems
collection.
By selecting another tab before removing the selected tab, you can delete a TabViewItem
even when it is currently selected in a TabView
control in WinUI 3.