c#ObservableCollection:如何实现CollectionChanged事件

时间:2016-08-17 21:37:13

标签: c# mvvm xamarin observablecollection

我想知道如何使用ObservableCollection和CollectionChanged事件。我有一个Canvas类,它在上面画笔画。我是否在Canvas类中放置了CollectionChanged事件处理程序并监听集合更改,还是将模型放入托管笔划集合中。

public partial class CollectionBindingPage : ContentPage
{
    private ObservableCollection<Object> c;

    public CollectionBindingPage()
    {
        InitializeComponent();

        c.CollectionChanged += (sender, e) => { 
            //Update the display when strokes was added or removed.
        };
    }


    public class Object
    {
        public string A { get; set; }
        public string B { get; set; }
    }

    public class ViewModel
    {
        public ObservableCollection<Object> collection { get; set; }
    }
}

抱歉,我是第一次使用此功能。

1 个答案:

答案 0 :(得分:3)

e属于NotifyCollectionChangedEventArgs类型,其中包含NewItemsOldItemsAction

c.CollectionChanged += (sender, e) => { 
    Console.WriteLine($"{e.Action}");
    // check e.Action and draw your stuff       
};

https://msdn.microsoft.com/en-us/library/system.collections.specialized.notifycollectionchangedeventargs(v=vs.110).aspx

在评论中草绘精神上的解决方案

class MyObject : INotifyPropertyChanged
{
    private string _a;
    public event PropertyChangedEventHandler PropertyChanged;

    public string A
    {
        get { return _a; }
        set
        {
            _a = value;
            OnPropertyChanged();
        }
    }

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

class Pagey : ContentPage
{
    private ObservableCollection<MyObject> c = new ObservableCollection<MyObject>();

    // somwhere in your code 
    c.CollectionChanged += OnCollectionChanged;

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
    {
        if (args.NewItems != null)
        {
            foreach (var item in args.NewItems.Cast<MyObject>())
            {
                item.PropertyChanged += OnChanged;
            }
        }

        if(args.OldItems != null)
        {
            foreach (var item in args.OldItems.Cast<MyObject>())
            {
                item.PropertyChanged -= OnChanged;
            }
        }

        Redraw();
    }

    private void OnChanged(object sender, PropertyChangedEventArgs e)
    {
        Redraw();
    }

    private void Redraw()
    {

    }
}