C# 在TabControl中防止页面的多个实例
我正在制作一个应用程序,在其中打开选项卡控件中的wpf页面。但我可以在tabcontrol中一次又一次地打开同一页。我希望一旦页面被打开,它就不能再被打开,如果我再次尝试打开它,它应该集中在tabcontrol上。我做了以下代码,但没有工作。我正在使用自定义的closableTabItem用户控件C# 在TabControl中防止页面的多个实例,c#,.net,wpf,xaml,tabcontrol,C#,.net,Wpf,Xaml,Tabcontrol,我正在制作一个应用程序,在其中打开选项卡控件中的wpf页面。但我可以在tabcontrol中一次又一次地打开同一页。我希望一旦页面被打开,它就不能再被打开,如果我再次尝试打开它,它应该集中在tabcontrol上。我做了以下代码,但没有工作。我正在使用自定义的closableTabItem用户控件 private void Set_Fee_Click(object sender, RoutedEventArgs e) { // Adding page to frame and then
private void Set_Fee_Click(object sender, RoutedEventArgs e)
{
// Adding page to frame and then adding that frame to tab item and then adding tab item to main tab.
FeeStructure feePage = new FeeStructure();
_closableTab = new ClosableTabItem();
_formFrame = new Frame();
_formFrame.Content = feePage;
_closableTab.Content = _formFrame;
_closableTab.Header = "Set Fee Structure";
if (!mainTab.Items.Contains(_closableTab))
{
mainTab.Items.Add(_closableTab);
_closableTab.Focus();
}
else
{
_closableTab.Focus();
}
}
private void Database_RecoveryBackup_Click(object sender, RoutedEventArgs e)
{
// Adding page to frame and then adding that frame to tab item and then adding tab item to main tab.
DbRecoveryBackup dbRecBack = new DbRecoveryBackup();
_closableTab = new ClosableTabItem();
_formFrame = new Frame();
_formFrame.Content = dbRecBack;
_closableTab.Content = _formFrame;
_closableTab.Header = "Data Base";
if (!mainTab.Items.Contains(_closableTab))
{
mainTab.Items.Add(_closableTab);
_closableTab.Focus();
}
else
{
_closableTab.Focus();
}
}
它永远不会发生,因为您每次都在创建
ClosableTabItem
的新实例,所以它每次都是唯一的,所以.Items.Contains
在这种情况下永远不会起作用,因为它使用object.Equals
匹配项
现在,既然您在问题中说您只需要一个ClosableTabItem
实例,那么
使用Linq,您可以检查项目中是否存在ClosableTabItem
类型的项目
...
// Here we're checking the array 'Items',
// if it contains any item whose type is 'ClosableTabItem'
if (!mainTab.Items.Any(item => item is ClosableTabItem)))
...
它永远不会发生,因为您每次都在创建
ClosableTabItem
的新实例,所以它每次都是唯一的,所以.Items.Contains
在这种情况下永远不会起作用,因为它使用object.Equals
匹配项
现在,既然您在问题中说您只需要一个ClosableTabItem
实例,那么
使用Linq,您可以检查项目中是否存在ClosableTabItem
类型的项目
...
// Here we're checking the array 'Items',
// if it contains any item whose type is 'ClosableTabItem'
if (!mainTab.Items.Any(item => item is ClosableTabItem)))
...
f是ClosableTabItem
将工作得更快。或者Items.OfType().Any()
f是可克隆的。项目
的工作速度要快得多。或Items.OfType().Any()