【问题标题】:Xamarin - How to Bind Data From Rest API to a StackLayout NOT ListViewXamarin - 如何将来自 Rest API 的数据绑定到 StackLayout 而不是 ListView
【发布时间】:2021-03-03 00:46:27
【问题描述】:

我正在尝试使用从我的 REST API 获取的数据将数据绑定到 StackLayout 内的标签,但它没有显示任何数据。

我能够获取数据,但我想知道如何使用 BindingContext 绑定该数据?我不想将数据绑定到 ListView,而是在 StackLayout 内。

ViewTask.xaml:

<StackLayout BackgroundColor="White" Padding="13, 5">
    <StackLayout Padding="13, 7">
        <Label Text="Task Name: " Font="Bold"/>
        <Label Text="{Binding Title}" />
    </StackLayout>
    <StackLayout Padding="13, 7">
        <Label Text="Created By: " Font="Bold"/>
        <Label Text="{Binding Creator}" />
    </StackLayout>
    <StackLayout Padding="13, 7">
        <Label Text="Status: " Font="Bold"/>
        <Label Text="{Binding Status}" />
    </StackLayout>
    <StackLayout Padding="13, 7">
        <Label Text="Date Created: " Font="Bold"/>
        <Label Text="{Binding Timestamp}" />
    </StackLayout>
    <StackLayout Padding="13, 7">
        <Label Text="Description: " Font="Bold"/>
        <Label Text="{Binding Description}" />
    </StackLayout>
</StackLayout>

ViewTask.xaml.cs

private int TaskId;

public HttpResponseMessage response;

private ObservableCollection<Task> _task;

public ViewTask(int tId)
{
    TaskId = tId;
    FetchTaskView();

    InitializeComponent();
}

async void FetchTaskView()
{
    Title = "Task #: " + TaskId;

    if (Connectivity.NetworkAccess == NetworkAccess.Internet)
    {
        var apiResponse = RestService.For<ITasksApi>(UserSettings.Url);
        response = await apiResponse.GetTasks();

        if (response.IsSuccessStatusCode)
        {
            var taskContent = JsonConvert.DeserializeObject<List<Task>>(await response.Content.ReadAsStringAsync());
            _task = new ObservableCollection<Task>(taskContent);

            BindingContext = _task.Where(t => t.Id == TaskId).ToList();
        }
    }
    else
    {
        UserDialogs.Instance.Toast("No internet connection. Unable to fetch task data.", TimeSpan.FromSeconds(5));
    }
}

【问题讨论】:

标签: c# visual-studio xamarin xamarin.forms data-binding


【解决方案1】:

您的任务类应该包含带有 getter 和 setter 的属性。

public class Task
{
   public string Title { get; set; }
   public string Creater { get; set; }
   .....
}

然后使用

BindingContext = _task.Where(t => t.Id == TaskId).SingleOrDefault();

【讨论】:

    【解决方案2】:
      <StackLayout BindableLayout.ItemsSource="{Binding YourList}">
                <BindableLayout.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding Your PropertyName}"/>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
            </StackLayout>
    

    这里是如何将列表绑定到 stacklayout 的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 2016-06-06
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多