【发布时间】:2017-11-03 09:03:30
【问题描述】:
我尝试了多种方法来尝试使其实时更新,因为我正在尝试制作一个简单的基于 GUI 的秒表。截至目前,我 NOT 试图让它看起来很漂亮,我只是想让程序运行。我已经包含了我尝试使用的方法来更新TextBlock。我尝试的最后一个是this.Dispatcher.Invoke( new Action(() => ... 方法。我尝试的另一种方法是使用我在 cmets 的代码中包含的 async-await 方法。
namespace WpfApp3
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private /*async*/ void start_Click(object sender, RoutedEventArgs e)
{
// await Task.Run(() =>
{
this.Dispatcher.Invoke( new Action(() =>
{
Stopwatch Timer = new Stopwatch();
Timer.Start();
TimeSpan goneby = Timer.Elapsed;
string time = String.Format("{0:00}:{1:00}.{2:00}",
goneby.Minutes, goneby.Seconds,
goneby.Milliseconds / 10);
TextBlock textBlock = new TextBlock();
textBlock.Width = 100;
textBlock.Height = 50;
textBlock.HorizontalAlignment = HorizontalAlignment.Center;
textBlock.VerticalAlignment = VerticalAlignment.Top;
textBlock.Text = time;
}));
// });
}
}
}
}
这里是 XAML,以防万一需要解决这个问题:
<Window x:Name="window1" x:Class="WpfApp3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d"
Title="New Window" Height="300" Width="300">
<Grid>
<Button x:Name="start" Content="Start" HorizontalAlignment="Left" VerticalAlignment="Top" Width="213" Margin="38,181,0,0" Height="50" Click="start_Click"/>
</Grid>
</Window>
【问题讨论】:
-
你需要使用计时器而不是秒表
-
Invoke在主 UI 线程上运行它,您需要使用BeginInvoke()和 here is a link 来回答我对类似问题的回答。 -
你定义了你的文本块,现在,只需将它添加到你的视觉元素之一。
标签: c# wpf xaml async-await dispatcher