C# 根据组合框值,更改刷新计时器
在C# 根据组合框值,更改刷新计时器,c#,wpf,xaml,C#,Wpf,Xaml,在.xaml.cs中,我有以下代码 DispatcherTimer timer = new DispatcherTimer(); // Default value for auto generation timer.Interval = new TimeSpan(0, 0, 5); timer.Start(); timer.Tick += timer_Tick; 在.xaml中,我有以下组合框 &
.xaml.cs
中,我有以下代码
DispatcherTimer timer = new DispatcherTimer();
// Default value for auto generation
timer.Interval = new TimeSpan(0, 0, 5);
timer.Start();
timer.Tick += timer_Tick;
在.xaml
中,我有以下组合框
<ComboBox Name="RefreshTick" SelectedIndex="0" SelectionChanged="RefreshTick_Change">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>3</ComboBoxItem>
<ComboBoxItem>4</ComboBoxItem>
<ComboBoxItem>5</ComboBoxItem>
</ComboBox>
但显然,return
不是正确的表达方式
有人能帮忙吗?有没有一种方法可以让我不需要五个if
语句,一个接一个地执行呢?试试这个(或者类似的方法):
我将在SelectedIndexChanged事件中尝试以下操作
timer.IsEnabled = false;
// Add timer tick event code??
timer.Interval = new TimeSpan(0, 0, RefreshTick.SelectedIndex );
timer.IsEnabled = true;
停止计时器,根据所选索引重置间隔,然后重新启动计时器。您可能还需要编写一些代码来完成计时器滴答声事件所做的任何事情 您必须检查计时器的空值。 因为combobox在启动期间触发SelectionChanged事件
private void RefreshTick_Change(object sender, SelectionChangedEventArgs e)
{
if (timer == null) return;
int period = Int32.Parse(((ComboBoxItem)RefreshTick.SelectedItem).Content.ToString());
timer.Interval = TimeSpan.FromSeconds(period);
timer.Stop();
timer.Start();
}
也许您可以尝试这样的方法:timer.Interval=newtimespan(0,0,RefreshTick.SelectedIndex);只要在组合框值更改时调用事件,但它会显示
timer.Stop()代码>在当前上下文中不存在:/code-behind中的哪个位置声明了计时器?如果要在RefreshTick_Change中访问它,需要在全局范围内声明它。它是'DispatcherTimer=new DispatcherTimer();`在mypublic MainWindow(){..}
code下,它在构造函数MainWindow中声明和定义。调度计时器;它需要在全局范围内声明(您也可以在全局范围内定义它,例如=new DispatchTimer()。或者您可以继续在MainWindow的构造函数中定义它。但它必须在全局范围内声明。我现在看到了;但是现在这些值根本没有刷新…我缺少什么吗?我全局声明DispatchTimer
,并在RefreshTick\u Change
方法中调用timer.Stop
等。唯一的问题是,timer.stop();
“在当前上下文中不存在”我假设Dispatchermer timer=new Dispatchermer();是一个类变量,可以在阅读文档后的组合框更改事件中使用。请尝试IsEnable,我将更新我的示例。
timer.IsEnabled = false;
// Add timer tick event code??
timer.Interval = new TimeSpan(0, 0, RefreshTick.SelectedIndex );
timer.IsEnabled = true;
private void RefreshTick_Change(object sender, SelectionChangedEventArgs e)
{
if (timer == null) return;
int period = Int32.Parse(((ComboBoxItem)RefreshTick.SelectedItem).Content.ToString());
timer.Interval = TimeSpan.FromSeconds(period);
timer.Stop();
timer.Start();
}