可观察集合添加对象不刷新视图

时间:2016-11-21 18:18:38

标签: android listview xamarin observablecollection inotifypropertychanged

这是我的代码,当我按下与Clicked属性addische绑定的按钮时,新项目将添加到ListView,但我无法在列表中看到它。

public partial class GS : ContentPage
{
    private GSViewModel _viewModel;

    public GS()
    {
        InitializeComponent();
        BindingContext = _viewModel = new GSViewModel();
    }

    private void addische(object sender, EventArgs e)
    {
        _viewModel.newItemAdded();
    }

    public class GSViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<schItem> _scheListItem;
        public ObservableCollection<schItem> Items { get { return _scheListItem; }
            private set
            {
                if (_scheListItem != value)
                {
                    _scheListItem = value;
                    OnPropertyChanged();
                }
            }
        }

        public void newItemAdded()
        {
            Items.Add(new schItem
            {
                realm_id = 133,
                list_id = 33
            });
        }

        public GSViewModel()
        {
            Items = new ObservableCollection<schItem>();
            initListView();
        }

        public void initListView()
        {
           //get data
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class schItem
    {
        public int realm_id { get; set; }
        public int list_id { get; set; }
        }
    }

也许我错过了INotifyPropertyChanged课程。

  

我在Android设备中调试

1 个答案:

答案 0 :(得分:1)

你可能没有看到任何东西的几个原因。

  1. 您的绑定错误,因此您不会看到任何文字。修复变更

          <Label Text = "{Binding name}" HeightRequest="20" FontAttributes="Bold"/>
          <Label Text = "{Binding data, StringFormat='a {0:F0}'}" />
    
  2.       <Label Text = "{Binding realm_id}" HeightRequest="20" FontAttributes="Bold"/>
          <Label Text = "{Binding list_id}" />
    
    1. 检查&#34; delete.png&#34;存在于正确的位置,而不是&#34; delete.jpg&#34;

    2. 修复后删除ListView IsEnabled =&#34; False&#34;

    3. enter image description here