【发布时间】:2020-11-07 14:38:38
【问题描述】:
我在将属性绑定到 Xamarin Forms 中的 ListView 时遇到问题。我想做的是:
{
InitializeComponent();
//Task.Run(async () => await GetTaskDetails());
GetTasks();
}
ObservableCollection<XMCTasks> _userTasks;
private async void GetTasks()
{
using (var client = new HttpClient())
{
string userId = "";
if(Application.Current.Properties["userId"] != null)
{
userId = Application.Current.Properties["userId"].ToString();
}
var uri = "http://diplomaxmcws-dev.us-east-2.elasticbeanstalk.com/api/Tasks/GetUserTasks?userId=" + userId;
var result = await client.GetStringAsync(uri);
var TaskList = JsonConvert.DeserializeObject<List<XMCTasks>>(result);
UserTasks = new ObservableCollection<XMCTasks>(TaskList);
}
}
public ObservableCollection<XMCTasks> UserTasks
{
get
{
return _userTasks;
}
set
{
_userTasks = value;
OnPropertyChanged();
}
}
从 Rest API 调用中获取对象列表,然后将这些对象绑定到 ListView:
<ListView ItemsSource="{Binding UserTasks}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<StackLayout>
<!-- <Label Text="{Binding XMCTask_Id, StringFormat='XMCTask_Id: {0:F0)}'}"></Label> -->
<Label Text="{Binding Task_Name, StringFormat='Task_Name: {0:F0)}'}" TextColor="Black" FontSize="Medium"></Label>
<!-- <Label Text="{Binding Task_Description, StringFormat='Task_Description: {0:F0)}'}"></Label>
<Label Text="{Binding Creator_Id, StringFormat='Creator_Id: {0:F0)}'}"></Label>
<Label Text="{Binding Referencer_Id, StringFormat='Referencer_Id: {0:F0)}'}"></Label>
<Label Text="{Binding XMCPune_Id, StringFormat='XMCPune_Id: {0:F0)}'}"></Label>
<Label Text="{Binding XMCProjekt_Id, StringFormat='XMCProjekt_Id: {0:F0)}'}"></Label>
<Button Text="{Binding XMCTipologjia_Id, StringFormat='XMCTipologjia_Id: {0:F0)}'}"></Button>-->
</StackLayout>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
我不知道它是否与 Xamarin 表单页面的生命周期有关。只是为了让您知道,成功登录后会加载此页面。由于从 Web 服务获取结果的过程是异步的,因此可能会出现问题。非常感谢任何方法。
【问题讨论】:
-
您还没有告诉我们真正的问题是什么。您是否能够从您的服务中获取数据?您能否找到 ItemsSource 的数据?您是否在绑定数据模板中的单个元素时遇到问题?您在哪里设置页面的 BindingContext?为什么要从构造函数调用异步方法?
-
对,我认为它会被暗示。是的,我的服务正在正确返回数据。我在构造函数中调用异步方法,因为我想在页面加载时显示该信息(任务)。由于我使用 xamarin 形式,.xaml 负责设计,.cs 是一种控制器,考虑到它,MMVM 是这种设计模式的调用方式。我认为设计中的 ItemsSource 属性就足够了,在“控制器”中声明绑定上下文可能至少是多余的。
-
你没有回答我的问题。您是否获得任何数据行?或者你得到没有绑定数据的行?你在设置 BindingContext 吗?如果要调用异步方法,请从 OnAppearing 执行,而不是构造函数。
-
是的,我从服务中获取数据。 OnAppearing 似乎正在工作,但从调试的角度来看,没有任何变化。在这两种情况下,绑定属性都得到了正确填充。我想更多地了解事情是如何执行的,因为似乎有点连贯。总之谢谢你!!
-
再一次,你在哪里设置
BindingContext?没有它,绑定将无法工作。尝试在构造函数中添加BindingContext = this;。
标签: c# listview xamarin xamarin.forms