How to implement event - c#

class Foo(){
public List<string> SomeCollection;
}
I need to implement an event which can fires when something added or removed from the Collection. How to do this?

List<T> has no notification support. You could look at BindingList<T>, which has events - or Collection<T>, which can be inherited with override methods.
If you want to expose the event at the Foo level, perhaps something like below - but it may be easier to leave it on the list:
class Foo{
public event EventHandler ListChanged;
private readonly BindingList<string> list;
public Foo() {
list = new BindingList<string>();
list.ListChanged += list_ListChanged;
}
void list_ListChanged(object sender, ListChangedEventArgs e) {
EventHandler handler = ListChanged;
if (handler != null) handler(this, EventArgs.Empty);
}
public IList<string> SomeCollection {get {return list;}}
}

Take a look at the BindingList and ObservableCollection classes (in the System.ComponentModel and System.Collections.ObjectModel namespaces respectively) - either one should do the job well for you.
Note that the two classes generally provide the same functionality, but they do differ slightly. BindingList is typically more suitable for data-binding/UI purposes (hence it's name), since it allows the option to cancel updates and such. However, ObservableCollection is possibly more appropiate in your case, since you're just interested in being notified of changes (it would seem), and the class was designed purely from that perspective. The fact that they exist in very different namespaces sort of hints at this. If you want the precise details on the similarities and differences, I recommend you inspect the linked MSDN docs.

You might take a look at this tutorial on making your own custom events.

You can do this by using an ObservableCollection instead of a List.

basic one...
here is a good link
public class Foo
{
private List<string> _SomeCollection;
public event EventHandler Added;
public void Add(string item)
{
SomCollection.Add(item);
OnAdd();
}
private void OnAdd()
{
if (Added != null)
{
Added.Invoke(this, EventArgs.Empty);
}
}
}

Related

c# wrap model object containing list for MVVM binding

Lets say I have a model object
class ModelClass
{
public List<Element> eList;
public void MethodA()
{
doSomething();
}
}
I would like to use this object in an MVVM as well. The Viewmodel would then invoke methods like MethodA to manipulate the data and the elements in eList would be updated. Is there a way to do this without making eList an ObservableCollection? I'd like to do so in order to use this ModelClass in other places as well without too much code polution.
If we compare List and ObservableCollection then both are implemented from IList. There isn't much of a difference there. The most difference is ObservableCollection also implements INotifyCollectionChanged interface, which allows WPF to bind to it.
Therefore, if you don't want to use List instead of ObservableCollection in your model class then you need to implement the class with INotifyCollectionChanged:
class ModelClass:INotifyCollectionChanged
{
public List<Element> eList;// call OnCollectionChanged() when you set/add/remove...the list).
public void MethodA()
{
doSomething();
}
#region INotifyCollectionChanged Members
protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
}

Trigger InotifyPropertyChanged/CollectionChanged on ObservableCollection

I've tried looking at other topics on this but I haven't found a working implementation to my question. Basically, I have an ObservableCollection called "FruitBasket" that contains different kinds of fruit. FruitBasket itself contains ObservableCollections for each respective type of fruit that passes through so that they can be used as ItemSources for ListViews (Denoted by their names "AppleContainer" and "OrangeContainer"), each displaying one kind of fruit. Because the fruit classes themselves implement INotifyPropertyChanged, modifying their values triggers updates to the ListView controls just fine, however, FruitBasket has a "TotalWeight" property derived from the weights of all the other fruits in the collections. I want "TotalWeight" to update the Label control in the UI without me having to refresh the UI. Triggerering a notification on a property change of the actual ObservableCollection itself, and not simply its constituent members is more difficult and I haven't found any solutions that work so far (or that I've implemented correctly).
public class FruitBasket : ObservableCollection<IFruit>
{
private decimal _totalWeight;
public FruitBasket()
{
this.Add(new OrangeContainer(this));
this.Add(new AppleContainer(this));
}
public OrangeContainer Oranges
{
get { return (OrangeContainer)this.Items[0]; }
}
public AppleContainer Apples
{
get { return (AppleContainer)this.Items[1]; }
}
public decimal TotalWeight
{
get { return _totalWeight; }
set { _totalWeight = value; }
}
internal void UpdateWeight(IFruit caller)
{
_totalWeight = 0;
foreach (Orange orng in (OrangeContainer)this.Items[0])
{
_totalWeight += orng.Weight;
}
foreach (Apple appl in (AppleContainer)this.Items[1])
{
_totalWeight += appl.Weight;
}
}
You need to call INotifyPropertyChanged.PropertyChanged event of your FruitBasket whenever items are added, removed or Weight property of any item has changed.
Let's split it into two tasks:
TotalWeight should be recalculated when items are added, removed, or items' weight is changed. We need to handle those events.
Raise FruitBasket.PropertyChanged event
I have splitted these two tasks into two classes in order to follow Single Responsibility Principle:
1) - this handles items' PropertyChanged events:
public abstract class ExtendedObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
protected override void ClearItems()
{
foreach (var item in Items) item.PropertyChanged -= ItemPropertyChanged;
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
item.PropertyChanged += ItemPropertyChanged;
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
this[index].PropertyChanged -= ItemPropertyChanged;
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
this[index].PropertyChanged -= ItemPropertyChanged;
item.PropertyChanged += ItemPropertyChanged;
base.SetItem(index, item);
}
abstract void ItemPropertyChanged(object sender, PropertyChangedEventArgs e);
}
2) - this recalculates TotalWeight when necessary
public class FruitBasket : ExtendedObservableCollection<IFruit>
{
protected override void ItemPropertyChanged(object sender, PropertyChangedEventArgs e){
UpdateWeight();
OnPropertyChanged("TotalWeight")
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
UpdateWeight();
OnPropertyChanged("TotalWeight")
base.OnCollectionChanged(e);
}
}
Of course your Fruit should implement INotifyPropertyChanged interface. You will find plenty of examples how to do it. It is very simple.
I found the root(s) of the problem(s). I'll start with the most obvious:
I wasn't as diligent in assigning datacontext in the UI for the Fruit Basket observable collection object itself as I was the for the members of its collection (OrangeContainer and AppleContainer). In the initialization of the UI window, assigning datacontext to the ListView objects is second nature. I wasn't quite matching the right node's datacontext in the XAML to the Fruit Basket object in the initialization method in the code behind (I really should have checked that earlier).
Because of the misaligned assignments of datacontext/binding, between the XAML and initialization method, the propertychanged event was never firing for my fruit basket observable collection like it was for the Apple and Orange objects inside the OrangeContainer and AppleContainer collections that were members of FruitBasket. So, in the Orange class declaration we'd have this:
public class Orange : INotifyPropertyChanged, IFruit
And the implementation like so
public event PropertyChangedEventHandler PropertyChanged;
public void PropChange(string prop)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
And when the PropChange method was called in the Weight property setter, this.PropertyChanged would not be null, and everything would work fine.
The FruitBasket class was a bit more tricky. Because of the aformentioned issue of improper matching in the UI Code, this.PropertyChanged would return null every time I tried to notify a change in property. However, it got a bit more confusing because unlike the Orange or Apple classes, it inherits ObservableCollection (ObservableCollection in the declaration if we want to be specific). I know ObservableCollection is really just a Collection class that implements INotifyPropertyChanged and INotifyCollectionChanged interfaces. It's really nice to see the plumbing now that .NET is open source (praise the lord)
http://referencesource.microsoft.com/#System/compmod/system/collections/objectmodel/observablecollection.cs
In any case, implementing this became more confusing, because I kept seeing this:
Warning 1 'TestingObsColNotify.FruitBasket.PropertyChanged' hides inherited member 'System.Collections.ObjectModel.ObservableCollection.PropertyChanged'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. C:\Testing VS Project\TestingObsColNotify\TestingObsColNotify\FruitBasket.cs 60 50 TestingObsColNotify
I still see this, but my implementation works, because while it was a result of the inheritance from INotifyProperty changed via ObservableCollection as seen in my original class declaration
public class FruitBasket : ObservableCollection<IFruit>
This was just shy of the last element need to make everything work, which was adding the INotifyPropertyChanged to the class itself like so:
public class FruitBasket : ObservableCollection<IFruit>, INotifyPropertyChanged
It seems a bit redundant and inelegant but I didn't get very far trying to override and wrestle with the inheritance of INotifyPropertyChanged from ObservableCollection (Or as best as I can understand).
So there we have it, everything works now, sans MVVM. I'll certainly move on to that pattern later, but it's nice to have resolved this issue instead of lazily just re-assigning the contents of controls in the code behind methods on the UI side of things.
Thank you to those who came in here and contributed, I appreciate you taking the time to respond.
If using binding, Add the interface INotifyPropertyChanged to your class. If you have ReSharper installed, accept the recommendation to implement the interface. Then, whenever you want to update any text box, call PropertyChanged with the name of the property TotalWeight, see https://softwareengineering.stackexchange.com/questions/228067/where-do-put-inotifypropertychanged-interface-in-model-or-viewmodel. Whenever you update any of the ObservableCollections, manually update the TotalWeight, then call the aforementioned PropertyChanged to tell the UI to update itself. I've used this technique to push updates from the ViewModel into the View (i.e. from the class into the XAML) for some fairly complex scenarios, it works very well.
I'd also recommend following the learning curve for MVVM, projects written in that way tend to be more scalable, are easier to maintain, and just easier to work with.

Short way to write an event?

Typically we use this code:
private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
add { _updateErrorIcons += value; }
remove { _updateErrorIcons -= value; }
}
Is there a similar shortcut like with automatic properties?
Something like:
public event EventHandler UpdateErrorIcons { add; remove; }
Yep. Get rid of the { add; remove; } part and the backing delegate field and you're golden:
public event EventHandler UpdateErrorIcons;
That's it!
Let me just add that before you asked this question, I hadn't even thought about the fact that the auto-implemented version of events is inconsistent with that of properties. Personally, I would actually prefer it if auto-implemented events worked the way you first attempted in your question. It would be more consistent, and it would also serve as a mental reminder that events are not identical to delegate fields, just like properties are not identical to regular fields.
Honestly, I think you're the rare exception where you actually knew about the custom syntax first. A lot of .NET developers have no clue there's an option to implement your own add and remove methods at all.
Update: Just for your own peace of mind, I have confirmed using Reflector that the default implementation of events in C# 4 (i.e., the implementation that gets generated when you go the auto-implemented route) is equivalent to this:
private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
add
{
EventHandler current, original;
do
{
original = _updateErrorIcons;
EventHandler updated = (EventHandler)Delegate.Combine(original, value);
current = Interlocked.CompareExchange(ref _updateErrorIcons, updated, original);
}
while (current != original);
}
remove
{
// Same deal, only with Delegate.Remove instead of Delegate.Combine.
}
}
Note that the above utilizes lock-free synchronization to effectively serialize add and remove calls. So if you're using the latest C# compiler, you don't need to implement add/remove yourself even for synchronization.
public event EventHandler UpdateErrorIcons;
is just fine
you can use
yourObbject.UpdateErrorIcons += YourFunction;
add {} and remove {} are used only in special cases where you need to handle event hookups manually. Us mere mortals normally just use public event EventHandler UpdateErrorIcons; where "EventHandler" is the delegate of choice.
For instance:
public delegate void MyEventDelegate(object sender, string param1);
public event MyEventDelegate MyEvent;
Note that because MyEvent is null if it doesn't have any listeners you need to check if it is null before invoking it. A standard method for doing this check is:
public void InvokeMyEvent(string param1)
{
MyEventDelegate myEventDelegate = MyEvent;
if (myEventDelegate != null)
myEventDelegate(this, param1);
}
A key element in this check is to make a copy of the object in question first and then work only on the copy. If not you could get a rare race condition where another thread unhooks between your if and your call.

C# Language Design: explicit interface implementation of an event

Small question about C# language design :))
If I had an interface like this:
interface IFoo {
int Value { get; set; }
}
It's possible to explicitly implement such interface using C# 3.0 auto-implemented properties:
sealed class Foo : IFoo {
int IFoo.Value { get; set; }
}
But if I had an event in the interface:
interface IFoo {
event EventHandler Event;
}
And trying to explicitly implement it using field-like event:
sealed class Foo : IFoo {
event EventHandler IFoo.Event;
}
I will get the following compiler error:
error CS0071: An explicit interface implementation of an event must use event accessor syntax
I think that field-like events is the some kind of dualism for auto-implemented properties.
So my question is: what is the design reason for such restriction done?
Interesting question. I did some poking around the language notes archive and I discovered that this decision was made on the 13th of October, 1999, but the notes do not give a justification for the decision.
Off the top of my head I don't see any theoretical or practical reason why we could not have field-like explicitly implemented events. Nor do I see any reason why we particularly need to. This may have to remain one of the mysteries of the unknown.
I guess it might have to do with the fact that you can't call an explicit interface implementation from other members of the class:
public interface I
{
void DoIt();
}
public class C : I
{
public C()
{
DoIt(); // error CS0103: The name 'DoIt' does not exist in the current context
}
void I.DoIt() { }
}
Note that you can call the method by upcasting to the interface first:((I)this).DoIt();. A bit ugly but it works.
If events could be explicitly implemented as ControlFlow (the OP) suggested, then how would you actually raise them? Consider:
public interface I
{
event EventHandler SomethingHappened;
}
public class C : I
{
public void OnSomethingHappened()
{
// Same problem as above
SomethingHappened(this, EventArgs.Empty);
}
event EventHandler I.SomethingHappened;
}
Here you cannot even raise the event by upcasting to the interface first, because events can only be raised from within the implementing class. It therefore seems to make perfect sense to require accessor syntax for explicitly implemented events.
When explicitly implementing an event that was declared in an interface, you must use manually provide the add and remove event accessors that are typically provided by the compiler. The accessor code can connect the interface event to another event in your class or to its own delegate type.
For example, this will trigger error CS0071:
public delegate void MyEvent(object sender);
interface ITest
{
event MyEvent Clicked;
}
class Test : Itest
{
event MyEvent ITest.Clicked; // CS0071
public static void Main() { }
}
The correct way would be:
public delegate void MyEvent(object sender);
interface ITest
{
event MyEvent Clicked;
}
class Test : Itest
{
private MyEvent clicked;
event MyEvent Itest.Clicked
{
add
{
clicked += value;
}
remove
{
clicked -= value;
}
}
public static void Main() { }
}
see Compiler Error CS0071
This would not actually be an original thought by myself.
However, I thought I might respond to this:
"Off the top of my head I don't see any theoretical or practical reason why we could not have field-like explicitly implemented events. Nor do I see any reason why we particularly need to. This may have to remain one of the mysteries of the unknown."
-Eric Lippert
In Chapter 23 of A Programmer's Introduction to C#, Second Edition, Eric Gunnerson wrote:
"[I]f another class also wanted to be called when the button was clicked, the += operator could be used, like this:
button.Click += new Button.ClickHandler(OtherMethodToCall);
Unfortunately, if the other class wasn't careful, it might do the following:
button.Click = new Button.ClickHandler(OtherMethodToCall);
This would be bad, as it would mean that our ButtonHandler would be unhooked and only the new method would be called."
...
"What is needed is some way of protecting the delegate field so that it is only accessed using += and -=."
He goes on over the next few pages to comment on including the add() and remove() methods to implement this behavior; being able to write to those methods directly and the consequence of storage allocation for unneeded delegate references.
I would add more, but I respect the author too much to do so without his permission. I recommend finding a copy of this book and would recommend anything by Eric Gunnerson in general (blog, etc...)
Anyway, I hope this is relevant to the topic and if so, hope it shines light on this "mystery of the unknown"? (I was reading this very chapter and searching Stack Overflow for insight into event handler logic considerations when creating custom collections from custom objects) - I only mention this because I claim no specific authority on this particular subject. I am merely a student in search of "enlightenment" myself :-)

Why is ReadOnlyObservableCollection.CollectionChanged not public?

Why is ReadOnlyObservableCollection.CollectionChanged protected and not public (as the corresponding ObservableCollection.CollectionChanged is)?
What is the use of a collection implementing INotifyCollectionChanged if I can't access the CollectionChanged event?
Here's the solution: CollectionChanged events on ReadOnlyObservableCollection
You have to cast the collection to INotifyCollectionChanged.
I've found a way for you of how to do this:
ObservableCollection<string> obsCollection = new ObservableCollection<string>();
INotifyCollectionChanged collection = new ReadOnlyObservableCollection<string>(obsCollection);
collection.CollectionChanged += new NotifyCollectionChangedEventHandler(collection_CollectionChanged);
You just need to refer to your collection explicitly by INotifyCollectionChanged interface.
I know this post is old, however, people should take their time to understand the patterns used in .NET before commenting. A read only collection is a wrapper on an existing collection that prevents consumers from modifying it directly, look at ReadOnlyCollection and you will see that it is a wrapper on a IList<T> which may or may not be mutable. Immutable collections are a different matter and are covered by the new immutable collections library
In other words, read only is not the same as immutable!!!!
That aside, ReadOnlyObservableCollection should implicitly implement INotifyCollectionChanged.
There are definitely good reasons for wanting to subscribe to collection changed notifications on a ReadOnlyObservableCollection. So, as an alternative to merely casting your collection as INotifyCollectionChanged, if you happen to be subclassing ReadOnlyObservableCollection, then the following provides a more syntactically convenient way to access the a CollectionChanged event:
public class ReadOnlyObservableCollectionWithCollectionChangeNotifications<T> : ReadOnlyObservableCollection<T>
{
public ReadOnlyObservableCollectionWithCollectionChangeNotifications(ObservableCollection<T> list)
: base(list)
{
}
event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged2
{
add { CollectionChanged += value; }
remove { CollectionChanged -= value; }
}
}
This has worked well for me before.
You might vote for the bug entry on Microsoft Connect that describes this issue: https://connect.microsoft.com/VisualStudio/feedback/details/641395/readonlyobservablecollection-t-collectionchanged-event-should-be-public
Update:
The Connect portal has been shutdown by Microsoft. So the link above does not work anymore.
My Win Application Framework (WAF) library provides a solution: ReadOnlyObservableList class:
public class ReadOnlyObservableList<T>
: ReadOnlyObservableCollection<T>, IReadOnlyObservableList<T>
{
public ReadOnlyObservableList(ObservableCollection<T> list)
: base(list)
{
}
public new event NotifyCollectionChangedEventHandler CollectionChanged
{
add { base.CollectionChanged += value; }
remove { base.CollectionChanged -= value; }
}
public new event PropertyChangedEventHandler PropertyChanged
{
add { base.PropertyChanged += value; }
remove { base.PropertyChanged -= value; }
}
}
As answered already, you have two options: you can either cast the ReadOnlyObservableCollection<T> to the interface INotifyCollectionChanged to access the explicitly implemented CollectionChanged event, or you can create your own wrapper class that does that once in the constructor and just hooks up the events of the wrapped ReadOnlyObservableCollection<T>.
Some additional insights into why this issue has not been fixed yet:
As you can see from the source code, ReadOnlyObservableCollection<T> is a public, non-sealed (i. e. inheritable) class, where the events are marked protected virtual.
That is, there might be compiled programs with classes that are derived from ReadOnlyObservableCollection<T>, with overridden event definitions but protected visibility. Those programs would contain invalid code once the event's visiblity is changed to public in the base class, because it is not allowed to restrict the visibility of an event in derived classes.
So unfortunately, making protected virtual events public later on is a binary-breaking change, and hence it will not be done without very good reasoning, which I am afraid "I have to cast the object once to attach handlers" simply isn't.
Source: GitHub comment by Nick Guerrera, August 19th, 2015
This was top hit on google so I figured I'd add my solution in case other people look this up.
Using the information above (about needing to cast to INotifyCollectionChanged), I made two extension methods to register and unregister.
My Solution - Extension Methods
public static void RegisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
{
collection.CollectionChanged += handler;
}
public static void UnregisterCollectionChanged(this INotifyCollectionChanged collection, NotifyCollectionChangedEventHandler handler)
{
collection.CollectionChanged -= handler;
}
Example
IThing.cs
public interface IThing
{
string Name { get; }
ReadOnlyObservableCollection<int> Values { get; }
}
Using the Extension Methods
public void AddThing(IThing thing)
{
//...
thing.Values.RegisterCollectionChanged(this.HandleThingCollectionChanged);
}
public void RemoveThing(IThing thing)
{
//...
thing.Values.UnregisterCollectionChanged(this.HandleThingCollectionChanged);
}
OP's Solution
public void AddThing(IThing thing)
{
//...
INotifyCollectionChanged thingCollection = thing.Values;
thingCollection.CollectionChanged += this.HandleThingCollectionChanged;
}
public void RemoveThing(IThing thing)
{
//...
INotifyCollectionChanged thingCollection = thing.Values;
thingCollection.CollectionChanged -= this.HandleThingCollectionChanged;
}
Alternative 2
public void AddThing(IThing thing)
{
//...
(thing.Values as INotifyCollectionChanged).CollectionChanged += this.HandleThingCollectionChanged;
}
public void RemoveThing(IThing thing)
{
//...
(thing.Values as INotifyCollectionChanged).CollectionChanged -= this.HandleThingCollectionChanged;
}
Solution
ReadOnlyObservableCollection.CollectionChanged is not exposed (for valid reasons outlined in other answers), so let's make our own wrapper class that exposes it:
/// <summary>A wrapped <see cref="ReadOnlyObservableCollection{T}"/> that exposes the internal <see cref="CollectionChanged"/>"/>.</summary>
public class ObservableReadOnlyCollection<T> : ReadOnlyObservableCollection<T>
{
public new NotifyCollectionChangedEventHandler CollectionChanged;
public ObservableReadOnlyCollection(ObservableCollection<T> list) : base(list) { /* nada */ }
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args) =>
CollectionChanged?.Invoke(this, args);
}
Explanation
People have asked why you would want to observe changes to a read-only collection, so I'll explain one of many valid situations; when the read-only collection wraps a private internal collection that can change.
Here's one such scenario:
Suppose you have a service that allows adding and removing items to an internal collection from outside the service. Now suppose you want to expose the values of the collection but you don't want consumers to manipulate the collection directly; so you wrap the internal collection in a ReadOnlyObservableCollection.
Note that in order to wrap the internal collection with ReadOnlyObservableCollection the internal collection is forced to derive from ObservableCollection by the constructor of ReadOnlyObservableCollection.
Now suppose you want to notify consumers of the service when the internal collection changes (and hence when the exposed ReadOnlyObservableCollection changes). Rather than rolling your own implementation you just want to expose the CollectionChanged of the ReadOnlyObservableCollection. Rather than forcing the consumer to make an assumption about the implementation of the ReadOnlyObservableCollection, you simply swap the ReadOnlyObservableCollection with this custom ObservableReadOnlyCollection, and you're done.
The ObservableReadOnlyCollection hides ReadOnlyObservableCollection.CollectionChanged with it's own, and simply passes on all the collection changed events to any attached event handler.

Categories