【发布时间】: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));
}
}
【问题讨论】:
-
你想要一个 BindableLayout - docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/…
标签: c# visual-studio xamarin xamarin.forms data-binding