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());
}
}
}
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