在Xamarin C#中以编程方式绑定ListView [英] programatically binding a listview in xamarin c#
问题描述
我想在Xamarin Portable中创建一个列表视图,
列表视图的项目源是List<String>
,而我的列表视图的数据模板是通过此函数准备的,
I want to create a listview in Xamarin portable,
the item source of the listview is List<String>
and my datatemplate of the listview is prepared by this function,
private DataTemplate createItemtemplate()
{
try
{
Label lbl_binding = new Label()
{
TextColor = Color.Red,
FontSize = 16,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
lbl_binding.SetBinding(Label.TextProperty, ".");
StackLayout stkBottom = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(0),
};
stkBottom.Children.Add(lbl_binding);
ViewCell vc = new ViewCell() {
View = stkBottom
};
DataTemplate Dp = new DataTemplate(() =>
{
return vc;
});
return Dp;
}
catch (Exception ex)
{
return null;
}
}
现在,我的列表视图已填充,但所有标签中都填充了最后一个项目,我的意思是正确地填充了所有项目,但所有项目仅填充了最后一个项目. 我在这里做错了什么?
Now, my list view is populated, but all the labels are filled with last item, I mean the no of items are rightly populated, but all the items are filled with the last item only. what i am doing wrong here?
lstAdmin = new ListView()
{
ItemTemplate = createItemtemplate(),
};
lstadmin.Itemsource = source;
推荐答案
public class AdminCell : ViewCell
{
public AdminCell()
{
Label lbl_binding = new Label()
{
TextColor = Color.FromRgb(30, 144, 255),
FontSize = 16,
VerticalTextAlignment = TextAlignment.Center,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
lbl_binding.SetBinding(Label.TextProperty, ".");
StackLayout stkBottom = new StackLayout()
{
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.Center,
Padding = new Thickness(0),
};
stkBottom.Children.Add(lbl_binding);
View = stkBottom;
}
}
此代码对我有用,删除了模板并使用此单元格,我仍然不明白为什么数据模板不起作用
this code is working for me removed the template and use this cell, i still don't understand why the data template is not working
这篇关于在Xamarin C#中以编程方式绑定ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!