我解决它的方法是使用我从以前版本改编的帮助类。基本上:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
namespace JTModelsWinStore.Local
{
public delegate void UseDataDelegate(DataCoordinator data);
public delegate bool GetDataDelegate(DataCoordinator data);
public class DataCoordinator
{
public DependencyObject Consumer;
public GetDataDelegate GetDataFunction;
public UseDataDelegate UseDataFunction;
public bool GetDataSucceeded;
public Exception ErrorException;
public string ErrorMessage;
public DataCoordinator(
DependencyObject consumer,
GetDataDelegate getDataFunction,
UseDataDelegate useDataFunction)
{
Consumer = consumer;
GetDataFunction = getDataFunction;
UseDataFunction = useDataFunction;
GetDataSucceeded = false;
ErrorException = null;
ErrorMessage = null;
}
public Task GetDataAsync()
{
GetDataSucceeded = false;
Task task = Task.Factory.StartNew(() =>
{
if (GetDataFunction != null)
{
try
{
GetDataSucceeded = GetDataFunction(this);
}
catch (Exception exception)
{
GetDataSucceeded = false;
ErrorException = exception;
ErrorMessage = exception.Message;
}
}
if (UseDataFunction != null)
{
if (Consumer != null)
{
var ignored = Consumer.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
UseDataFunction(this);
});
}
else
UseDataFunction(this);
}
});
return task;
}
}
}
然后在 Windows 商店代码中:
private async void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
DataCoordinator data = new DataCoordinator(this, Logon, LogonCompleted);
await data.GetDataAsync();
}
private bool Logon(DataCoordinator data)
{
LoggedOnUserID = ServiceClient.LogOn(UserName, Password);
if (LoggedOnUserID == null)
{
UserName = "AnonymousUser";
Password = "";
if (!String.IsNullOrEmpty(ServiceClient.ErrorMessage))
data.ErrorMessage = "Log on failed.";
return false;
}
if (!String.IsNullOrEmpty(ServiceClient.ErrorMessage))
{
data.ErrorMessage = ServiceClient.ErrorMessage;
return false;
}
return true;
}
private void LogonCompleted(DataCoordinator data)
{
if (data.GetDataSucceeded && LoggedOnUserID != null)
pageTitle.Text = "Logged On";
else
pageTitle.Text = "LogOn Failed";
}
我为助手提供了两个功能,一个用于获取数据(慢速),另一个用于处理 UI 中的数据。我知道我可以在两个嵌套的 lambdas 中做到这一点,但我喜欢隐藏两个 lambdas,这对于像我这样的老前辈来说更舒服。
为了他人的利益和我自己的利益,请随时批评它。