Earlier today I saw a nice post by Wei-Meng Lee with a tip on how to update the UI from an asynchronous thread in Windows Phone (thanks to Ginny Caughey). After reading it, I decided to whip up a little helper function that I thought others might find useful:
Without further ado, here is the helper function:
[csharp]
public void UpdateUI(Action displayCall)
{
if (Dispatcher.CheckAccess() == false)
{
Dispatcher.BeginInvoke(() =>
displayCall()
);
}
else
{
displayCall();
}
}
[/csharp]
To use the helper, you can call it like this:
[csharp]
UpdateUI(() =>
{
// Your UI Update Code Here
});
[/csharp]
Or like this:
[csharp]
public void TestDisplay()
{
// Your UI Update Code Here
}
[…]
UpdateUI(TestDisplay);
[/csharp]
Update: In response to Clint Rutkas’ question, there are several different ways you could do something like this to get info on a UI element. Here’s an example:
[csharp]
public T GetUIElementValue<T>(Func<T> getvalueCall)
{
T returnVal = default(T);
if (Dispatcher.CheckAccess() == false)
{
Dispatcher.BeginInvoke(() =>
returnVal = getvalueCall()
);
}
else
{
returnVal = getvalueCall();
}
return returnVal;
}
double GetSliderValue()
{
return Slider1.Value;
}
[/csharp]
And then to use it, you’d call it like this:
[csharp]
double SliderValue = GetUIElementValue<double>(GetSliderValue);
[/csharp]
You could build a function that checked a bunch of different elements and then returned a bool depending on the values. Of course these helper functions won’t work as written for all situations, but they’re pretty flexible and can be modified in many different ways to accommodate a lot of different needs.
Leave a reply to isenthil Cancel reply