WPF:Window加载的刷新/更新控件
|
我想在Label中显示时间.加载窗口时,需要自动刷新标签内容. 我有一个带有Label控件的简单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事件但是徒劳无功.永远不会显示窗口内容. 我可以做什么来加载窗口时自动更新标签? 解决方法这是完全正常的,因为OnLoad处理程序保持无限循环.该循环位于UI线程上,因此Window永远不会显示.首先:将循环包装在Backgroundworker中,使其在单独的线程上运行. 我还将循环代码分解为实现INotifyPropertyChanged的单独对象,该对象使用time(字符串)公开属性,使该属性在其更改时(通过循环)引发PropertyChanged事件.当然,您仍需要在单独的线程上执行此操作(例如,使用BackgroundWorker).使用Binding将专用对象绑定到标签. 另一种策略是使用定时器进行回调的定时器,你可以在那里更新标签. (编辑:清远站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

