我正在尝试在新应用程序中使用旧代码。我有以下问题。
我需要在新代码中调用与this.Loaded += OnLoaded
类似的内容。但我不能,因为我班上没有: Page
。
旧代码:
public sealed partial class VotePage : Page
{
public VotePage()
{
this.InitializeComponent();
// This will call the OnLoaded function
this.Loaded += OnLoaded;
}
旧代码(OnLoaded函数):
public async void OnLoaded(object sender, RoutedEventArgs e)
{
var response = await start();
dynamic dynJson = JsonConvert.DeserializeObject(response);
foreach (var item in dynJson)
{
Object votedGame = localSettings.Values[item.slug.ToString()];
string voted = "Collapsed";
string btnVoted = "VOTE";
bool btnEnabled = true;
if(votedGame != null)
{
voted = "Visible";
btnVoted = "VOTED!";
btnEnabled = false;
}
listofGames.Add(new Games { Title = item.name, Votes = item.votes, Slug = item.slug, Voted = voted, BtnVoted = btnVoted, BtnEnabled = btnEnabled });
}
gamesList.ItemsSource = listofGames;
}
新代码:
public class GamesList
{
public List<Game> Games { get; set; }
public String Name { get; set; }
public GamesList(String databaseName)
{
Name = databaseName;
// This won't work because there is no await.
Games = DataService.GetGames;
}
DataService.GetGames函数:
public async Task<List<Game>> GetGames()
{
Debug.WriteLine("GET for games.");
var response = await start();
dynamic dynJson = JsonConvert.DeserializeObject(response);
foreach (var item in dynJson)
{
Object votedGame = localSettings.Values[item.slug.ToString()];
string voted = "Collapsed";
string btnVoted = "VOTE";
bool btnEnabled = true;
if (votedGame != null)
{
voted = "Visible";
btnVoted = "VOTED!";
btnEnabled = false;
}
listofGames.Add(new Game { Title = item.name, Votes = item.votes, Slug = item.slug, Voted = voted, BtnVoted = btnVoted, BtnEnabled = btnEnabled });
}
return new List<Game>();
}
答案 0 :(得分:2)
根据GamesList类的初始化位置,时间和方式,您可以根据@Romasz链接的博客文章中的建议为其提供静态创建方法:
public sealed class GamesList
{
public List<Game> Games { get; set; }
public String Name { get; set; }
private GamesList(String databaseName)
{
Name = databaseName;
}
public static async Task<GamesList> Create(string databaseName)
{
GamesList instance = new GamesList(databaseName);
instance.Games = await DataService.GetGames();
return instance
}
...
}
然后,您将使用工厂方法创建异步实例并初始化该类:
public VotePage()
{
this.InitializeComponent();
this.Loaded += OnLoaded;
}
public async void OnLoaded(object sender, RoutedEventArgs e)
{
DataContext = await GamesList.Create("database name...");
}