问题描述
我有一个TabControl
,我要防止在其中添加现有的TabPage
(它们由名称标识),而是将SelectedTabPage
设置为此精确选项卡.
I have a TabControl
in which I want to prevent adding existing TabPage
(they are identified by a name) and instead set the SelectedTabPage
to this precise tab.
我想知道是否有一个事件在将页面添加到TabControl
之前立即触发.如果不是,使用TabPages
(列表)的事件CollectionChanged
是正确的选择吗?
I wish to know if there are an event that triggers right before a page is being added to the TabControl
. If not, would using the event CollectionChanged
of the TabPages
(list) be a correct alternative ?
推荐答案
尝试类似的方法,我正在检查TabControl
页面集合中是否有与尝试添加的页面同名的页面.存在,我将焦点设置在现有实例上,否则将新页面添加到TabControl
.看看这样的事情是否对您有用.
Try something like this, I am checking the TabControl
page Collection for a page with the same name as the Page that is trying to be added, if it exists I am setting focus to the existing instance, otherwise adding the new page to the TabControl
. See if something like this works for you.
private void button1_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage();
tp.Name = tabPage1.Name;
var temp =tabControl1.Controls.Find(tp.Name,true);
if( temp.Length > 0)
{
tabControl1.SelectedTab = (TabPage) temp[0];
}
else
tabControl1.Controls.Add(tp);
}
Anything having to do with the ControlCollection
will most likely be triggered after the control has been added.
从上面的链接:
如果您希望通过在TabControl
中添加ExtensionMethod
来清理代码,请检查现有页面,设置焦点或从此处添加.
If you want you could cleanup your code some by adding an ExtensionMethod
to your TabControl
Check for an existing page, set focus or add from there.
示例:
namespace ExtensionMethods
{
public static class MyExtensions
{
public static bool AddPage(this TabControl tc, TabPage tp)
{
var matchedPages = tc.Controls.Find(tp.Name, false);
if ( matchedPages.Length > 0)
{
tc.SelectedTab = (TabPage)matchedPages[0];
return true;
}
else
{
tc.TabPages.Add(tp);
tc.SelectedTab = tp;
return false;
}
}
}
}
用法:
tabControl1.AddPage(tp);
这篇关于TabControl AddingTab事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!