Listview不通过ViewModel绑定

时间:2018-03-23 05:45:27

标签: c# listview xamarin xamarin.forms viewmodel

我在ListViewViewModel绑定时遇到了问题。我创建了一个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);

2 个答案:

答案 0 :(得分:1)

我认为您忘记为ItemSource

设置ListView属性
sicCodeList.ItemSource = leader.Products;

更多信息here

答案 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");
}