如何通过循环更新wpf文本块的文本?
我有一个 wpf 应用程序,在该应用程序中我有一个按钮和一个文本块。我点击了按钮,在事件响应程序中我做了一个简单的循环。在该循环中,我等待了 2 秒,等待后我更新了文本块的文本,但似乎文本块没有随文本更新。相反,它更新一次(最后一次使用第一项 tex)。任何人都可以知道..如何在循环中更新文本块....
public partial class MainWindow : Window
{
List<String> list;
public MainWindow()
{
InitializeComponent();
LoadList();
}
private void LoadList()
{
list = new List<string>();
list.Clear();
list.Add("Chisty");
list.Add("Forkan");
list.Add("Farooq");
}
private void BtnClickHandler(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(5000); // wait for 5 second
textBlock1.Text = list[i].ToString(); // assign a new text to the textblock
System.Console.WriteLine(list[i].ToString());
}
}
}
I have a wpf application and in that application i have a button and a textblock. I have cliked the button and in the event responder i have done a simple looping. In that loop i have waited for 2 second and after the waiting i have updated the text of the textblock but it seems that the textblock is not updating with the text. Rather it is updated once(at the last time with the first item tex). Can anyone know.. how to update the textblock in a loop ....
public partial class MainWindow : Window
{
List<String> list;
public MainWindow()
{
InitializeComponent();
LoadList();
}
private void LoadList()
{
list = new List<string>();
list.Clear();
list.Add("Chisty");
list.Add("Forkan");
list.Add("Farooq");
}
private void BtnClickHandler(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(5000); // wait for 5 second
textBlock1.Text = list[i].ToString(); // assign a new text to the textblock
System.Console.WriteLine(list[i].ToString());
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要通知更改,您需要实现
Dispatcher
试试这个...
您可以在 Implement Application.DoEvents 中查看更多信息在 WPF 中
To notify the change you need to implement the
Dispatcher
Try this...
You can see more information in Implement Application.DoEvents in WPF
您的文本块未更新的原因是因为您阻止了调度程序。
让循环发生在新线程上,并要求调度程序更新文本块。
The reason you're textblock isn't updating is because you're blocking the dispatcher.
Let the loop occur on a new thread and ask the dispatcher to update the textblock.
您需要使用 MessageListener 和 DispatcherHelper 类来实现您的逻辑,以按一定时间间隔更新文本,因为它是在代码项目中的启动屏幕示例中实现的:
http://www.codeproject.com/KB/WPF/WPFsplashscreen.aspx
You need to implement your logic using MessageListener and DispatcherHelper classes to update text at some interval as it is implemented in this splash screen example in code project :
http://www.codeproject.com/KB/WPF/WPFsplashscreen.aspx