将Web Service方法分配给Xamarin Forms中ListView的ItemSource

时间:2016-07-19 06:58:30

标签: c# listview azure xamarin

我需要在我的应用程序中使用Azure Mobile Service,并在项目中添加Azure Mobile Client SDK。为了在我的项目中实现Web服务,我设置了我的AzureService类 -

    public partial class AzureService 
    {
        static AzureService defaultInstance = new AzureService ();

        MobileServiceClient client;

        IMobileServiceTable<modelLifeStyleDiets> modelLifeStyleDietsTable;

        public AzureService ()
        {
            this.client = new MobileServiceClient(url);

            this.modelLifeStyleDietsTable = client.GetTable<modelLifeStyleDiets>();

        }

        public static AzureService DefaultManager{      
            get{
                return defaultInstance;
                }
            private set{ 
                defaultInstance = value;
            }
        }

        public MobileServiceClient CurrentClient{
            get{ return client;}
        }

        public bool IsOfflineEnabled{
            get{ return modelLifeStyleDietsTable is Microsoft.WindowsAzure.MobileServices.Sync.IMobileServiceSyncTable<modelLifeStyleDiets>; }
        }


        public async Task<ObservableCollection<modelLifeStyleDiets>> GetTodoItemsAsync (bool syncItems = false)
        {
            try {

                IEnumerable<modelLifeStyleDiets> items = await modelLifeStyleDietsTable
                    .Where(Item => !(Item.done)).ToEnumerableAsync ();

                return new ObservableCollection<modelLifeStyleDiets> (items);
            } catch (MobileServiceInvalidOperationException msioe) {
                Debug.WriteLine (@"Invalid sync operation: {0}", msioe.Message);
            } catch (Exception e) {
                Debug.WriteLine (@"Sync error: {0}", e.Message);
            }
            return null;
        }


        public async Task SaveTaskAsync (modelLifeStyleDiets item)
        {
            if (item.id == null) {
                await modelLifeStyleDietsTable.InsertAsync (item);
            } else {
                await modelLifeStyleDietsTable.UpdateAsync (item);
            }
        }
    }

我的服务模型如下 -

    public class modelLifeStyleDiets
    {
        public string id { get; set; }
        public string itemName { get; set; }
        public bool done{ get; set;}
    }

我有ListView,我需要从服务中获取数据并将其分配给ListView的ItemSource。 我试过这个 -     listof_lifestyleDiets.ItemsSource = AzureService.DefaultManager.GetTodoItemsAsync();

但是在上面的代码中我得到了缺少类型转换的错误。如何解决?

1 个答案:

答案 0 :(得分:0)

您需要等待异步任务。

listof_lifestyleDiets.ItemsSource = await AzureService.DefaultManager.GetTodoItemsAsync();

您还需要确保绑定要显示的属性。

<ListView.ItemTemplate>
  <DataTemplate>
    <TextCell Text="{Binding itemName}" />
  </DataTemplate>
</ListView.ItemTemplate>

或者如果您以编程方式构建UI

nameLabel.SetBinding(Label.TextProperty, "itemName");