我需要更改以下方法:
public static IList<SomeItem> GetProjects() {
List<SomeItem> projects = new List<SomeItem>();
string result = Task.Run(() => TestMethodAsync("getProjects",GetApiKeyAsync())).GetAwaiter().GetResult();
MyObject resultparsed = new JavaScriptSerializer().Deserialize<MyObject>(result);
foreach (SomeItem item in resultparsed.result.items)
{
projects.Add(item);
}
return projects;
}
该项目将自动添加到ComboBox
:
这来自 XAML :
<ComboBox ItemsSource="{Binding Path=ProjectList}" IsSynchronizedWithCurrentItem="True" />
在这里,我正在尝试修改上述代码 C#:
public List<string> ProjectList { get; internal set; }
public static IList<SomeItem> GetProjects()
{
ProjectList = new List<string>;//???
string result = Task.Run(() => TestMethodAsync("getProjects",GetApiKeyAsync())).GetAwaiter().GetResult();
MyObject resultparsed = new JavaScriptSerializer().Deserialize<MyObject>(result);
foreach (SomeItem item in resultparsed.result.items)
{
ProjectList.Add(item);//??
}
}
答案 0 :(得分:1)
将List<string>
替换为ObservableCollection<string>
:
public ObservableCollection<string> ProjectList { get; internal set; }
与List<T>
不同,ObservableCollection<T>
在添加或删除项时向UI提供通知。
然后您可以填充源集合,如下所示:
public ObservableCollection<string> ProjectList { get; internal set; } = new ObservableCollection<string>();
public async Task PopiuateProjectListAsync()
{
ProjectList.Clear();
MyObject resultparsed = await Task.Run(() =>
{
string result = TestMethodAsync("getProjects", GetApiKeyAsync());
return new JavaScriptSerializer().Deserialize<MyObject>(result);
});
foreach (SomeItem item in resultparsed.result.items)
{
ProjectList.Add(item.SomeStringProperty);
}
}