我嘗試了多種方法來試圖讓它實時更新,因爲我試圖製作一個簡單的基於GUI的秒錶。截至目前,我是不是試圖讓它看起來很漂亮,我只是想讓程序運行。我已經包含了我試圖用來更新TextBlock
的方法。我嘗試的最後一個是this.Dispatcher.Invoke(new Action(() => ...
方法。我嘗試的另一種方法是使用我在註釋中的代碼中包含的async-await
方法。在wpf中實時更新文本框,給出沒有輸出的錯誤
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>
你需要使用計時器不秒錶 – Krishna
'Invoke'運行它在主UI線程什麼你需要使用'BeginInvoke()'和[這裏是一個鏈接](https://stackoverflow.com/a/39926050/2029607)來解決類似問題。 – XAMlMAX
現在,您定義了您的文本塊,只需將其添加到您的某個視覺元素上即可。 – GBursali