我在ListView
与ViewModel
绑定时遇到了问题。我创建了一个ViewModel
类的对象,并将其设置为ListView
的BindingContext。初始化时,此对象包含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);
答案 0 :(得分:1)
答案 1 :(得分:1)
最好将页面的BindingContext设置为ViewModel。然后,您可以将列表绑定到listview的ItemsSource:
private LeadershipViewModel leader = new LeadershipViewModel();
public MyPage()
{
InitializeComponent();
BindingContext = leader;
ListView sicCodeList = new ListView() { ... set properties ... };
sicCodeList.SetBinding(ListView.ItemsSourceProperty, "Products");
}