我正在开发一个带有全景页面的 Windows Phone 7 应用程序。
这个页面有两个项目,第一个带有一些文本,第二个带有控制图。第二个加载时间太长,所以我决定以这种方式加载它:
namespace Tested
{
public partial class DemoDetail : PhoneApplicationPage
{
private bool isFirstNavigateToMap;
private BackgroundWorker bgWorker;
private Map map;
public DemoDetail()
{
InitializeComponent();
map = null;
isFirstNavigateToMap = true;
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
map = new Map();
}
private void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (map != null)
mapGrid.Children.Add(map);
}
private void Panorama_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
Panorama panorama = (Panorama)sender;
PanoramaItem panoramaItem = (PanoramaItem)(panorama.SelectedItem);
if ((isFirstNavigateToMap) && (panoramaItem.Name.Equals("mapPanoramaItem")))
{
isFirstNavigateToMap = false;
bgWorker.RunWorkerAsync();
}
}
}
}
但是当我移动到第二个全景项目时,我在线得到了这个异常map = new Map();
:
No se controló System.UnauthorizedAccessException
Message=Invalid cross-thread access.
StackTrace:
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex, IntPtr constructDO)
at System.Windows.DependencyObject..ctor(UInt32 nativeTypeIndex)
at System.Windows.UIElement..ctor(UInt32 nKnownTypeIndex)
at System.Windows.FrameworkElement..ctor(UInt32 nKnownTypeIndex)
at System.Windows.Controls.Control..ctor(UInt32 nKnownTypeIndex)
at System.Windows.Controls.ContentControl..ctor()
at Microsoft.Phone.Controls.Maps.Core.MapBase..ctor()
at Microsoft.Phone.Controls.Maps.Core.MapCore..ctor()
at Microsoft.Phone.Controls.Maps.Map..ctor()
at Demonstration.DemoDetail.bgWorker_DoWork(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnRun(Object argument)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
如何异步创建和加载控制图?