我在用ViewModel
绑定ListView
时遇到问题。我已经创建了一个ViewModel
类的对象,并将其设置为ListView
的绑定上下文。此对象在初始化时包含 4 个项目,但ListView
仍为空。我不确定我在这里错过了什么。我在下面添加了代码 -
public class LeadershipViewModel
{
private PfsServiceArea _oldProduct;
public ObservableCollection Products { get; set; }
public LeadershipViewModel()
{
Products = new ObservableCollection();
var PFSArea = new PfsServices().GetPFSServiceArea("Leadership");
if (PFSArea.Count > 0){
foreach(PfsServiceArea pf in PFSArea){
Products.Add(pf);
}
}
}
public void ShowOrHidePoducts(PfsServiceArea product)
{
if (_oldProduct == product)
{
// click twice on the same item will hide it
product.ShowDescription = false;
product.ShowDisplay = true;
UpdateProducts(product);
}
else
{
if (_oldProduct != null)
{
// hide previous selected item
product.ShowDescription = true;
product.ShowDisplay = false;
UpdateProducts(_oldProduct);
}
// show selected item
product.ShowDescription = true;
product.ShowDisplay = false;
UpdateProducts(product);
}
_oldProduct = product;
}
private void UpdateProducts(PfsServiceArea product)
{
var index = Products.IndexOf(product);
Products.Remove(product);
Products.Insert(index, product);
}
我已经用下面这样的ListView
绑定了它——
Private LeadershipViewModel leader = new LeadershipViewModel();
sicCodeList = new CustomListview(ListViewCachingStrategy.RetainElement)
{
HorizontalOptions = LayoutOptions.StartAndExpand,
VerticalOptions = LayoutOptions.EndAndExpand,
ItemTemplate = sicDataTemplate,
SeparatorVisibility = SeparatorVisibility.None,
Margin = new Thickness(-5, 0, 0, 0),
BindingContext = leader
};
sicCodeList.HasUnevenRows = true;
//sicCodeList.BindingContext = leader;
sicCodeList.SetBinding(ListView.ItemsSourceProperty, "Products");
sicCodeList.ItemTapped += (sender, e) => OnItemTapped(sender, e);
最好将
页面的 BindingContext 设置为您的 ViewModel。然后,您可以将列表绑定到列表视图的项目源:
private LeadershipViewModel leader = new LeadershipViewModel();
public MyPage()
{
InitializeComponent();
BindingContext = leader;
ListView sicCodeList = new ListView() { ... set properties ... };
sicCodeList.SetBinding(ListView.ItemsSourceProperty, "Products");
}
我想你忘了为你ListView
设置ItemSource
属性
sicCodeList.ItemSource = leader.Products;
更多信息在这里