【问题标题】:WPF : Refresh / Update control on Window loadWPF:窗口加载时刷新/更新控件
【发布时间】: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 事件运行,但徒劳无功。窗口内容从不显示。

如何在加载窗口时自动更新标签?

【问题讨论】:

    标签: wpf controls


    【解决方案1】:

    这是完全正常的,因为 OnLoad 处理程序处于无限循环中。该循环在 UI 线程上,因此 Window 永远不会显示。

    首先:将循环包装在 Backgroundworker 中,使其在单独的线程上运行。

    我还将循环代码分解为一个实现INotifyPropertyChanged 的单独对象,该对象公开一个带有时间(字符串)的属性,让该属性在它发生变化时引发PropertyChanged 事件(通过循环)。当然,您仍然需要在单独的线程上执行此操作(例如使用BackgroundWorker)。使用 Binding 将您的专用对象绑定到标签。

    另一种策略是使用Timer,它会定期进行回调,您可以在那里更新标签。

    【讨论】:

      【解决方案2】:

      我将编写一个实现 INotifyPropertyChanged 接口的类,该接口具有 CurrentTime 属性并包含一个 DispatcherTimer 实例,该实例将定期引发 PropertyChanged("CurrentTime") 事件。

      然后只需将此对象放入表单的资源中,并将标签的内容绑定到 CurrentTime 属性。

      DispatcherTimer 使用消息泵,因此不涉及不必要的线程。

      【讨论】:

        【解决方案3】:

        使用 DispatcherTimer 代替无限循环

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-20
          • 2010-11-03
          • 2013-05-06
          • 2013-07-17
          • 2010-10-29
          • 1970-01-01
          相关资源
          最近更新 更多