我在我的一个网站 ( YinYangMoney ) 上使用 TabControls 进行导航,并构建了一些扩展方法来帮助我使用标签名称选择标签。以下是适合您的片段。
扩展类:
using System;
using System.Linq;
using System.Windows.Controls;
namespace MyApplication
{
internal static class Extensions
{
// Extension for TabControl
internal static void SelectTab(this TabControl tabControl, this TabItem tabItem)
{
if (tabControl == null || tabItem == null)
return null;
SelectTab(tabControl, tabItem.Tag);
}
// Extension for TabControl
internal static void SelectTab(this TabControl tabControl, string tabTagName)
{
if (tabControl == null)
return null;
// Find the TabItem by its Tag name
TabItem mainTabItem = tabControl.FindByTag(tabTagName);
if (mainTabItem == null)
return;
// Check to see if the tab needs to be selected
if (tabControl.SelectedItem != mainTabItem)
tabControl.SelectedItem = mainTabItem;
}
// Extension for TabControl
internal static TabItem FindByTag(this TabControl tabControl, string tagFragment)
{
if (tabControl == null || tagFragment == null)
return null;
return tabControl.Items
.OfType<TabItem>()
.Where(item => item.Tag != null && item.Tag.ToString().StartsWithIgnoreCase(tagFragment))
.FirstOrDefault();
}
// Extension for string
internal static bool StartsWithIgnoreCase(this string source, string target)
{
return source.StartsWith(target, StringComparison.CurrentCultureIgnoreCase);
}
}
}
TabControl 和 TabItems 的 XAML 看起来像这样:
<Controls:TabControl x:Name="x_TabControl">
<Controls:TabItem Header="Welcome" Tag="/Home/Welcome" x:Name="x_WelcomeTab" />
<Controls:TabItem Header="FAQ" Tag="/Home/FAQ" />
<Controls:TabItem Header="Contact Us" Tag="/Home/Contact_Us" />
<Controls:TabItem Header="Privacy Policy" Tag="/Home/Privacy_Policy" />
<Controls:TabItem Header="My Account" Tag="/Home/My_Account" />
</Controls:TabControl>
您可以像这样选择 Welcome TabItem:
x_TabControl.SelectTab("/Home/Welcome");
或者
x_TabControl.SelectTab(x_WelcomeTab);