我正在编写程序,在一个TabControl
中以编程方式添加选项卡。每个选项卡的内容都是使用UserControl
填充的:
private void process_addTab(string head, string type)
{
TabItem tab = new TabItem();
tab.Header = head;
switch (type)
{
case "trophy2": tab.Content = new Scoreboard2(); break;
case "trophy4": tab.Content = new Scoreboard4(); break;
case "text": tab.Content = new TextFields(); break;
case "talk": tab.Content = new LowerThirds(); break;
case "image": tab.Content = new ImageSelect(); break;
case "timer": tab.Content = new Timer(); break;
case "hitbox": tab.Content = new Hitbox(); break;
case "twitch": tab.Content = new Twitch(); break;
case "twitter": tab.Content = new Twitter(); break;
case "ustream": tab.Content = new Ustream(); break;
}
tabControl.Items.Add(tab);
}
这很好用。但是,当我从TabControl
中删除选项卡时,问题就出现了。每个选项卡都有一个按钮,可以将该特定选项卡从控件中删除:
public static void RemoveClick(TabControl tabControl)
{
if (MessageBox.Show("Are you sure you wish to remove this tab?", "Remove Tab",
MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
{
TabItem item = (TabItem)tabControl.SelectedItem;
tabControl.Items.Remove(tabControl.SelectedItem);
}
}
这种方法看起来可以很好地去掉选项卡。但是它有点具有误导性。在一些控件中,我有定时器函数运行
DispatcherTimer
。例如,Twitch控件内部有一个定时器,每30秒轮询Twitch API以获取频道信息。如果我删除选项卡,定时器仍然会继续运行;即使它不应该存在了。有任何解决办法吗?假设我对C#不太熟悉;因为我确实不太熟悉。
timer.IsEnabled = false
。或者,您可以通过处理选项卡内容的Loaded
和Unloaded
事件,并分别将IsEnabled
设置为true
或false
来管理其状态。 - Mike Strobel