![](/img/trans.png)
[英]Get value of a string Variable from MainPage.xaml.cs file to MainPage.xaml file in Windows Phone
[英]Windows phone C# updating text to GUI mainpage.xaml.cs?
我正在嘗試將文本從線程更新到主GUI線程,但拋出異常,因為它在不同的線程中。 我嘗試使用Dispatcher.CheckAccess(),BeginInvoke()但該項目不是Silverlight或WPF。 我嘗試舊樣式InvokeRequired,Invoke(),但這些都不可用。
StartTest.cs:
public StartTest(MainPage mainPage)
{
mainPageObj = mainPage;
}
public async Task RunTest(string testCase)
{
await Task.Run(() => RunTestCase(testCase));
}
public bool RunTestCase(string testcase)
{
switch (testcase)
{
case "testcase1":
int i = 0;
while (i < 10000)
{
i++;
}
mainPageObj.UpdatePassFail(true);//update the main GUI
break;
case "testcase2":
mainPageObj.UpdatePassFail(false);//update the main GUI
break;
}
return false;
}
MainPage.xaml.cs中:
public void UpdatePassFail(bool pass)
{
try
{
if (pass == true)
{
passCount++;
passFailCount = passCount + failCount;
textBlock_passTotal.Text = passCount.ToString();
textBlock_passFailTotal.Text = passFailCount.ToString();
}
else if (pass == false)
{
failCount++;
passFailCount = passCount + failCount;
textBlock_failTotal.Text = failCount.ToString();
textBlock_passFailTotal.Text = passFailCount.ToString();
}
}
catch(Exception error)
{
textBlock_tapInfo.Text = error.Message;
}
}
更新:
將以下語句放在第一個if語句中后,更新的數據顯示在主GUI中。
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
textBlock_passTotal.Text = passCount.ToString();
textBlock_passFailTotal.Text = passFailCount.ToString();
});
您應該在WP 8.1中使用CoreDispatcher
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
//UI code goes here
}
);
請參閱有關CoreDispatcher
MSDN鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.