【发布时间】:2009-03-29 22:50:53
【问题描述】:
我想在标签中显示时间。标签内容需要在加载窗口时自动刷新。
我有一个简单的 WPF 窗口,其中包含一个标签控件。如图所示
<Window x:Class="shoes.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<Label Margin="12" Name="lblSeconds"></Label>
<Button Margin="68,22,135,0" Name="button1" Height="24" VerticalAlignment="Top" Click="button1_Click">Button</Button>
</Grid>
</Window>
我查看了这里的代码:http://geekswithblogs.net/NewThingsILearned/archive/2008/08/25/refresh--update-wpf-controls.aspx
我修改为适合这种方式:
public partial class Window1 : Window
{
private static Action EmptyDelegate = delegate() { };
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
if (IsLoaded)
{
LoopingMethod();
}
}
private void LoopingMethod()
{
while(true)
{
lblSeconds.Content = DateTime.Now.ToLongTimeString();
lblSeconds.Refresh();
Thread.Sleep(10);
}
}
}
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate() { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}
}
我发现代码在通过 button_Click 事件触发时运行良好。我试图让代码通过这样的 Window_Loaded 事件运行,但徒劳无功。窗口内容从不显示。
如何在加载窗口时自动更新标签?
【问题讨论】: