【发布时间】:2012-03-09 18:13:48
【问题描述】:
这就是我想要做的。在我的 WP7 应用程序中,我正在加载一个包含两个 StackPanel 的页面。 StackPanel1 为“折叠”,StackPanel2 为“可见”。在加载页面时,我启动了一个 HttpWebRequest,然后异步处理 BeginGetResponse。此时我只想交换两个 StackPanel 的 Visibility。但是,由于 BeginGetResponse 是异步运行的,因此我不再处于 UI 线程中并且无法操作这些 StackPanel 控件。如果我尝试引用它们,当然,我会得到“非静态字段、方法或属性 'blah.StackPanel1' 需要对象引用”
这一切都说得通,我明白了。
以下是我尝试过的一些方法:
- 代表,但无论如何我都需要对我的控件进行静态引用。失败。
- 我尝试创建对我的页面类的静态引用,然后使用它来引用 BeginGetResponse 中的控件。这已编译,但我得到了 UnauthorizedAccessException 'invalid cross-thread access'。在运行时,当我尝试引用控件时。
- 搜索再搜索再搜索。
- 使用 Deployment.Current.Dispatcher.BeginInvoke 在 UI 线程上运行。
如何静态引用这些控件?
或者有没有更好的方法来做我正在做的事情?
编辑:
这是我的 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);
}
另一个编辑:
这是我尝试使用 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);
【问题讨论】:
-
请显示一些代码,我想我知道你的问题,但我不能确定。尽可能显示所有相关代码。
标签: windows-phone-7 reference static