WPF:在窗口加载时刷新/更新控件

3
我希望在标签中显示时间。当窗口加载时,标签内容需要自动刷新。
我有一个简单的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事件来运行代码,但是一直失败。窗口内容从未显示。

我该怎么做才能在窗口加载时自动更新标签?

3个回答

3
这很正常,因为OnLoad处理程序处于无限循环中。该循环在UI线程上运行,因此窗口永远不会显示。
首先:使用Backgroundworker将您的循环包装在其中,以便它在单独的线程上运行。
我还会将循环代码分解到实现INotifyPropertyChanged的单独对象中,该对象公开具有时间(字符串)的属性,并在其更改时引发PropertyChanged事件(通过循环)。当然,您仍需要在单独的线程上执行此操作(例如使用BackgroundWorker)。使用绑定将您的专用对象绑定到标签。
另一种策略是使用Timer,在定期间隔内进行回调,您可以在那里更新标签。

3
我会编写一个实现INotifyPropertyChanged接口的类,其中包含一个DispatcherTimer实例和一个CurrentTime属性。DispatcherTimer定期引发PropertyChanged("CurrentTime")事件。
然后只需将此对象放入表单资源中,并将标签内容绑定到CurrentTime属性即可。
DispatcherTimer使用消息泵,因此没有不必要的线程参与。

1

不要使用无限循环,而是使用 DispatcherTimer


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接