user2130951
user2130951

Reputation: 2741

Using delegates with custom parameters in events

I have the code as seen below. The problem that I am having is that this part of the code gives a compilation error.

Changed(this, new ListChangedEventArgs(Operation.Add, e.Value, 1));

Error 1 Using the generic type 'CustomDatastructures.Core.ListChangedEventArgs' requires 1 type arguments

Second problem is how to call the onChanged method.


//public delegate void ListChanged<TEventArgs>(object sender, TEventArgs e);
public delegate void BeforeListChanged<TEventArgs>(object sender, TEventArgs e);
public delegate void ListChanged<TEventArgs>(object sender, TEventArgs e);

// Make this class generic by adding a type-parameter to the class
public class ObservableList<T> : IEnumerable<T>
{
    // Declare an private variabel to work as 
    // the internal data storage for the list
    List<T> observerList = new List<T>();

    public event ListChanged<ListChangedEventArgs<T>> Changed;
    //public event BeforeListChanged<T> BeforeChanged;

    protected virtual void OnChanged(object sender, Operation op, T value, int count)
    {
        if (Changed != null)
            Changed(this, new ListChangedEventArgs(op, value, count));
    }



    /// <summary>
    /// Add and object to the list
    /// </summary>
    /// <param name="item">An object</param>
    public void Add(T item)
    {
        observerList.Add(item);
        OnChanged(this, Operation.Add, item, 1);
    }

This is the definition for the ListChangedEvent class

public class ListChangedEventArgs<T> : EventArgs
{
public int Count { get; }
public Operation Operation { get; }
public T Value { get; }
public ListChangedEventArgs(Operation operation, T value, int count)
}

Upvotes: 1

Views: 777

Answers (1)

PVitt
PVitt

Reputation: 11750

You are declaring your ObservableCollection of type T. This collection has an event ListChanged<T>. But you call this event as if it is ListChanged<ListChangedEventArgs<T>>. So you have to change your event's declaration:

public event ListChanged<ListChangedEventArgs<T>> Changed;
protected virtual void OnChanged(object sender, ListChangedEventArgs<T> e)
{
    if (Changed != null)
        Changed(this, e);
}

Upvotes: 2

Related Questions