I would like to update the Text of a TextBlock
in a WPF app. I am using a BackgroundWorker
which makes an asynchronous call to an update method.
Edit:
I had look at question: Progress Bar update from Background worker stalling
before posting. Where my problem differs is that I only want to change the text to "Loading..." in before a call to a potentially long running service call. I would like my implementation to be as reusable as possible and don't need to and can't keep track of progress. I then intend to change the textblock text back to its previous message.
I have modelled the problem in a new WPF project and am getting the same issue.
The text is changed to "Loading..." at the beginning of a datagrid begin cell edit event and is set back to its previous value when the necessary data is loaded.
My issue at the moment is that the text appears to change to "Loading..." and back again instantly, at the end of the cell begin edit event. I am certain that there is a significant time between the calls, even trying Wait(10000)
. I do not see the "Loading" text when I run it.
My implementation (note: I have already tried removing the using
enclosing, no change):
using(BackgroundWorker bw = new BackgroundWorker())
{
bw.WorkerReportsProgress = true;
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync("Loading...");
};
The code above is called within grdBlah_BeginningEdit
is called again after the data is grabbed, with the text changed.
void bw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
if (((BackgroundWorker)sender).CancellationPending)
{
e.Cancel = true;
return;
}
UpdateDelegate update = new UpdateDelegate(UpdateText);
this.Dispatcher.BeginInvoke(update, e.Argument);
// I have also tried: txtSearchCollection.Dispatcher.BeginInvoke(update, e.Argument);
}
catch (Exception ex)
{
bool brake = true; // used to apply a breakpoint
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
worker.RunWorkerCompleted -= new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
worker.DoWork -= new DoWorkEventHandler(bw_DoWork);
}
catch (Exception ex)
{
bool brake = true;
}
}
private delegate void UpdateDelegate(string s);
private void UpdateText(string s)
{
txtSelectedCollection.Text = s;
}
Any help would be greatly appreciated.