我正在程序中以编程方式向 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 以获取 channel 信息。如果我移除标签,计时器仍会继续运行;即使它不应该再存在了。
知道如何解决这个问题吗?假装我不太了解 C#;因为我没有。
最佳答案
通常,当用户控件从视口(viewport)中移除时,WPF 不会处理它们。这会在某些应用程序中引起麻烦(请参阅 Disposing WPF User Controls 以获得更广泛的讨论)。
要解决更具体的问题(例如停止计时器),请处理 TabItem
上的 Unloading
事件并禁用那里的计时器(参见 https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.tabitem)。
这是一个高级示例(子类化 TabItem
只是作为封装计时器的示例):
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TimerTabItem item = new TimerTabItem();
item.Unloaded += ItemOnUnloaded;
tabControl.Items.Add(item);
}
private void ItemOnUnloaded(object sender, RoutedEventArgs routedEventArgs)
{
(sender as TimerTabItem).Dispose();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
tabControl.Items.Remove(tabControl.Items[0]);
}
}
class TimerTabItem : TabItem, IDisposable
{
private DispatcherTimer MyTimer { get; set; }
public TimerTabItem() : base()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 0, 3);
timer.Tick += TimerOnTick;
timer.Start();
MyTimer = timer;
}
private void TimerOnTick(object sender, EventArgs eventArgs)
{
MessageBox.Show("Hello!");
}
#region Implementation of IDisposable
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
MyTimer.Stop();
MyTimer.Tick -= TimerOnTick;
MyTimer = null;
}
#endregion
}
关于c# - WPF 删除选项卡不处理内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26848254/