如何从 Xamarin 中的 ViewModel 获取数据 [英] How to get data from ViewModel in Xamarin

查看:32
本文介绍了如何从 Xamarin 中的 ViewModel 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

public class ViewCustomerViewModel
{
    public Customer CustomerInfo { get; set; }
    public static string baseUrl = "https://xxxx/Customers/";
    public ViewCustomerViewModel()
    {
        CheckUserinfo();
    }
    public async void CheckUserinfo()
    {
        .....
        var url = baseUrl;
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", xxx);
        string jsonStr = await client.GetStringAsync(url);
        var res = JsonConvert.DeserializeObject<Customer>(jsonStr);

        CustomerInfo = res;
    }
}

CustomerInfo 返回 oke

我有 PageOne.xaml

I have PageOne.xaml

<ContentPage ...>
  <ContentPage.BindingContext>
    <locals:ViewCustomerViewModel/>
  </ContentPage.BindingContext>
  <ContentPage.Content>
     
      <Label Text={Binding xxxx} />

  </ContentPage.Content>
</ContentPage>

PageOne.xaml.cs

PageOne.xaml.cs

这就是我将数据获取到绑定的方式:

This is how I get the data to Binding:

public Customer CustomerInfo { get; set; }
public PageOne()
{
    InitializeComponent();
    BindingContext = new ViewCustomerViewModel();
}

然而:在 PageOne.xaml 页面中,当我 <Label Text={Binding xxxx}/>--->绑定 xxxx,我没有得到 Customer 类的值.

However: in PageOne.xaml page when I <Label Text={Binding xxxx} /> ---> Binding xxxx, I get no value of Customer class.

我做错了什么.请帮助我如何显示 CustomerInfo 结果.谢谢

I was doing something wrong. Please help me how can I display CustomerInfo results. Thank you

更新

PageOne.xaml

PageOne.xaml

<ContentPage ...>      
  <ContentPage.Content>
     
      <Label Text={Binding xxxx} />

  </ContentPage.Content>
</ContentPage>

推荐答案

问题是构造函数完成的时候,实例还在异步初始化,没有明显的方法判断异步初始化什么时候完成.

The problem is that when the constructor completes, the instance is still being asynchronously initialized, and there isn’t an obvious way to determine when the asynchronous initialization has completed.

不要从构造函数中调用,而是从页面的 OnAppearing 方法中调用,您可以将其设为异步.

Instead of calling from the constructor, do it from the page's OnAppearing method, which you can make async.

或者你可以改变你的视图模型,制作一个 工厂模式 for it.从链接中,您可以参考多种方法.

Or you could change your viewmodel,make a Factory Pattern for it.From the link,there are several methods you could refer to.

这篇关于如何从 Xamarin 中的 ViewModel 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆