这里有一个简单的 WPF 程序:
<!-- Updater.xaml -->
<Window x:Class="Update.Updater"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<StackPanel>
<Button Click="Button_Click" Height="50"></Button>
<Label Content="{Binding Label1Text}" Height="50"></Label>
<Label Content="{Binding Label2Text}" Height="50"></Label>
</StackPanel>
</Grid>
</Window>
// Updater.xaml.cs
using System.Threading;
using System.Windows;
namespace Update
{
public partial class Updater : Window
{
public Updater()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Label1Text = "It is coming...";
Thread.Sleep(3000);
Label2Text = "It is here!";
}
public string Label1Text
{
get { return (string)GetValue(CategoryProperty); }
set { SetValue(CategoryProperty, value); }
}
static readonly DependencyProperty CategoryProperty = DependencyProperty.Register("Label1Text", typeof(string), typeof(Updater));
public string Label2Text
{
get { return (string)GetValue(Label2TextProperty); }
set { SetValue(Label2TextProperty, value); }
}
static readonly DependencyProperty Label2TextProperty = DependencyProperty.Register("Label2Text", typeof(string), typeof(Updater));
}
}
目的是当您单击按钮时,第一个标签显示It is coming...
. 然后程序休眠 3 秒,最后显示第二个标签It is here!
。但是,下面的幼稚实现不起作用。如果您运行它并单击按钮,则会发生以下情况:程序休眠 3 秒,然后同时显示两个标签文本。您知道如何更正程序以使其按预期运行吗?