Here is what I am trying to do. In my WP7 app, I am loading a page that has two StackPanels. StackPanel1 is "Collapsed" and StackPanel2 is "Visible". On load of the page, I am kicking off an HttpWebRequest and then processing the BeginGetResponse asynchronously. At this point I just want to swap the Visibility of the two StackPanels. However, since the BeginGetResponse is run Asynchronously, I am no longer in the UI thread and cannot manipulate these StackPanel controls. If I try to reference them, of course, I get "An object reference is required for the non-static field, method, or property 'blah.StackPanel1'"
This all makes sense and I get why.
Here are some things I have tried:
- Delegates, but any way I sliced it, I needed a static reference to my controls. fail.
- I tried to create a static reference to my page class and then use that to reference my controls in the BeginGetResponse. This compiled, but I got a UnauthorizedAccessException 'invalid cross-thread access.' at run-time when I tried to reference the controls.
- Searching and searching and searching.
- Using Deployment.Current.Dispatcher.BeginInvoke to run on the UI thread.
How can I statically reference these controls?
OR is there a better way to do what I'm doing?
EDIT:
Here is my HttpWebRequest
if (NetworkInterface.GetIsNetworkAvailable())
{
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp("http://urlThatWorks.com");
httpWebRequest.Method = "GET";
httpWebRequest.BeginGetResponse((asyncresult) =>
//do processing of my return here
//then here is the problem
StackPanel1.Visibility = System.Windows.Visibility.Visible;
StackPanel2.Visibility = System.Windows.Visibility.Collapsed;
}, httpWebRequest);
}
ANOTHER EDIT:
And here is how I tried with Deployment.Current.Dispatcher.BeginInvoke
httpWebRequest.BeginGetResponse((asyncresult) =>
//do processing of my return here
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
StackPanel1.Visibility = System.Windows.Visibility.Visible;
StackPanel2.Visibility = System.Windows.Visibility.Collapsed;
});
}, httpWebRequest);