【发布时间】:2021-10-17 16:52:17
【问题描述】:
我试图从我的Country 模型中显示CountryText。它似乎拿起了数组并在列表视图中显示了空白文本块,但 CountryText 没有显示。
我刚开始学习数据绑定,所以我不确定我是否遗漏了什么
XML
<Window x:Class="CovidApi.View.CasesWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="clr-namespace:CovidApi.ViewModel"
xmlns:local="clr-namespace:CovidApi.View"
mc:Ignorable="d"
Title="CasesWindow"
Height="450"
Width="800">
<Window.Resources>
<vm:CasesVM x:Key="vm"/>
</Window.Resources>
<DockPanel DataContext="{StaticResource vm}">
<Grid>
<ListView Width="160"
ItemsSource="{Binding Countries}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding CountryText}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
<Grid>
<ListView Width="160">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
<Grid>
</Grid>
</DockPanel>
</Window>
视图模型
namespace CovidApi.ViewModel
{
public class CasesVM : INotifyPropertyChanged
{
public ObservableCollection<Country> Countries { get; set; }
public CasesVM()
{
Countries = new ObservableCollection<Country>();
}
public async void MakeQuery()
{
var countries = await Covid19Helper.GetLatestAllCountries();
Countries.Clear();
foreach (var country in countries)
{
Countries.Add(country);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
API 助手
namespace CovidApi.ViewModel.Helpers
{
public class Covid19Helper
{
public static async Task<List<Country>> GetLatestAllCountries()
{
List<Country> countries = new();
string url = "https://covid-19-tracking.p.rapidapi.com/v1";
using (HttpClient client = new())
{
client.DefaultRequestHeaders.Add("x-rapidapi-key", "**apiKey**");
client.DefaultRequestHeaders.Add("x-rapidapi-host", "covid-19-tracking.p.rapidapi.com");
var response = await client.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
countries = JsonConvert.DeserializeObject<List<Country>>(json);
}
return countries;
}
}
}
型号
public class Country
{
public string ActiveCasesText { get; set; }
public string CountryText { get; set; }
public string LastUpdate { get; set; }
public string NewCasesText { get; set; }
public string NewDeathsText { get; set; }
public string TotalCasesText { get; set; }
public string TotalDeathsText { get; set; }
public string TotalRecoveredText { get; set; }
}
Array showing in left ListView
但是被反序列化的变量 - countries = JsonConvert.DeserializeObject<List<Country>>(json); 将 Country 模型的所有属性显示为 null
【问题讨论】:
-
您的示例代码中似乎包含了您的 API 密钥。我建议删除它,特别是因为您已经提供了一个示例 API 响应。
-
我已经删除了它,但这并不是什么大不了的事。它只是一个学习工具
标签: c# wpf data-binding api-design