Rob*_*urd 1 c# wpf xaml c#-4.0
首先,感谢您抽出宝贵时间阅读这篇文章.
我有一个计时器类,每60秒从我的SQL数据库下载一次"产品".即检查可能已被其他用户编辑的更新产品.
这是我的班级代码:
public class GetProducts : INotifyPropertyChanged
{
public GetProducts()
{
Timer updateProducts = new Timer();
updateProducts.Interval = 60000; // 60 second updates
updateProducts.Elapsed += timer_Elapsed;
updateProducts.Start();
}
public ObservableCollection<Products> EnabledProducts
{
get
{
return ProductsDB.GetEnabledProducts();
}
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("EnabledProducts"));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Run Code Online (Sandbox Code Playgroud)
然后我将其绑定到我的XAML(WPF)控件的tag属性:
<Page.Resources>
<!-- Products Timer -->
<products_timer:GetProducts x:Key="getProducts_timer" />
</Page.Resources>
Tag="{Binding Source={StaticResource getProducts_timer}, Path=EnabledProducts, Mode=OneWay}"
Run Code Online (Sandbox Code Playgroud)
这非常有效.我遇到的问题是,当托管控件的窗口或页面关闭时,无论如何,计时器都会继续打开.
一旦Page/Control不再可用,有人可以建议一种方法来停止自动收报机吗?
再次感谢您的时间.非常感谢所有帮助.
首先保持对计时器的引用:
private Timer updateProducts;
public GetProducts()
{
updateProducts = new Timer();
......
}
Run Code Online (Sandbox Code Playgroud)
创建另一个方法,StopUpdates
例如,调用时将停止计时器:
public void StopUpdates()
{
updateProducts.Stop();
}
Run Code Online (Sandbox Code Playgroud)
现在在窗口的OnUnloaded事件中停止计时器:
private void MyPage_OnUnloaded(object sender, RoutedEventArgs e)
{
var timer = this.Resources["getProducts_timer"] as GetProducts;
if (timer != null)
timer.StopUpdates();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
952 次 |
最近记录: |