how to update the text of a wpf textblock through a loop?
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].ToS开发者_C百科tring());
}
}
}
To notify the change you need to implement the Dispatcher
Try this...
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();
DoEvents();
System.Console.WriteLine(list[i].ToString());
}
}
public void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame(true);
Dispatcher.CurrentDispatcher.BeginInvoke
(
DispatcherPriority.Background,
(SendOrPostCallback)delegate(object arg)
{
var f = arg as DispatcherFrame;
f.Continue = false;
},
frame
);
Dispatcher.PushFrame(frame);
}
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.
private delegate void UpdateTextBox();
private void BtnClickHandler(object sender, RoutedEventArgs e)
{
string text;
UpdateTextBox updateTextBox = () => textBlock1.Text = text;
Action a = (() =>
{
for (int i = 0; i < 3; i++)
{
System.Threading.Thread.Sleep(500); // wait for 5 second
text = list[i].ToString();
textBlock1.Dispatcher.Invoke(updateTextBox); // assign a new text to the textblock
System.Console.WriteLine(list[i].ToString());
}
});
a.BeginInvoke(null, null);
}
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
精彩评论