我的UWP应用程序中有DispatcherTimer
用于从Web服务更新数据库。
public DispatcherTimer SessionTimer { get; set; }
在此计时器的tick事件中更新数据库之前,我会折叠主网格并显示更新消息,更新完成后我会反转。
private void SessionTimer_Tick(object sender, object e)
{
rpWait.Visibility = Visibility.Visible;
LayoutRoot.Visibility = Visibility.Collapsed;
Update();
rpWait.Visibility = Visibility.Collapsed;
LayoutRoot.Visibility = Visibility.Visible;
}
我的XAML代码:
<Grid x:Name="LayoutRoot" Style="{StaticResource backGrid}">
<RelativePanel Style="{StaticResource rpTop}">
...
</RelativePanel>
<Frame x:Name="frameBody" Loaded="frameBody_Loaded" Margin="0,100,0,0"/>
</Grid>
<RelativePanel x:Name="rpWait" Visibility="Collapsed">
<StackPanel RelativePanel.AlignHorizontalCenterWithPanel="True" RelativePanel.AlignVerticalCenterWithPanel="True">
<TextBlock x:Name="lbMessage" FontSize="30" HorizontalAlignment="Center">Updating</TextBlock>
<TextBlock x:Name="lbWaiting" FontSize="30" Margin="0 50 0 0">Please Wait</TextBlock>
</StackPanel>
</RelativePanel>
但是计时器没有显示任何内容(DB正确更新)。
请帮帮我?
答案 0 :(得分:0)
我相信你的问题是你不运行Update()Asynchronous并等待更新。另外,如果您更好地进行UI更新,则可以在UI线程中执行它们。
DispatcherTimer ds = new DispatcherTimer();
// In Constuctor of the page
ds.Interval = new TimeSpan(0, 1, 0);
ds.Tick += ds_Tick;
ds.Start();
void ds_Tick(object sender, object e)
{
ShowHide(true);
await Update();
ShowHide(false);
}
private async void ShowHide(bool state)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if(state)
{
rpWait.Visibility = Visibility.Visible;
LayoutRoot.Visibility = Visibility.Collapsed;
}
else
{
rpWait.Visibility = Visibility.Collapsed;
LayoutRoot.Visibility = Visibility.Visible;
}
});
}
private Task Update()
{
//run your update
//if your update doesnt have await use
//return Task.Run(() => {
// //doto
// });
//If it does just write your code
}