大家好,
我试图使用API来显示当前的比特币价格。 API会返回结果和所有内容,但它只是在UWP应用程序中显示它。
奇怪的是,它确实显示了一次结果,但之后它再也没有显示出结果。
这是我的MainPage代码:
public sealed partial class MainPage : Page, INotifyPropertyChanged
{
public string Price { get; set; }
private DispatcherTimer _timer;
public event PropertyChangedEventHandler PropertyChanged;
public MainPage()
{
this.InitializeComponent();
this._timer = new DispatcherTimer();
this._timer.Interval = TimeSpan.FromSeconds(20);
this._timer.Tick += OnUpdate;
this._timer.Start();
}
private async void OnUpdate(object sender, object e)
{
this.Price = (await API.GetData(1))[0]["price_eur"];
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Price"));
}
}
以下是我的API类代码:
class API
{
public static async Task<List<Dictionary<string, string>>> GetData(int limit)
{
var url = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR&limit=" + limit;
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(result);
}
else
{
return null;
}
}
}
}
这是我的MainPage xaml代码:
<RelativePanel>
<Rectangle x:Name="rctOrange" Fill="Orange" RelativePanel.AlignRightWithPanel="True" RelativePanel.AlignBottomWithPanel="True" Stretch="UniformToFill"/>
<TextBlock x:Name="tbPrice" FontSize="80" Text="{x:Bind Price, Mode=OneWay}" RelativePanel.AlignVerticalCenterWith="rctOrange" RelativePanel.AlignHorizontalCenterWith="rctOrange"/>
</RelativePanel>
我希望你们能找到问题因为我疯了。
提前致谢!
答案 0 :(得分:1)
您不应在页面上实现INotifyPropertyChanged。您应该创建一个实现INotifyPropertyChanged的ViewModel。
private async void OnUpdate(object sender, object e)
{
this.Price.Value = (await API.GetData(1))[0]["price_eur"];
}
class PriceModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _value;
public string Value
{
get { return _value; }
set
{
_value = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
}