-1

I have an bitmap and an property like this :

 private Bitmap host_Bitmap; private Bitmap Host_Bitmap {get;set;} 

How can I create an event when the host_Bitmap change?

2

1 Answer 1

3

If you want to take the simple route for one property, you add an event, and in the set you invoke it:

public event EventHandler BitmapChanged; private Bitmap _hostBitmap; public Bitmap HostBitmap { get => _hostBitmap; set{ _hostBitmap = value; BitmapChanged?.Invoke(this, EventArgs.Empty); } } 

If you want to pass more info about the event you can provide a modified EventArgs subclass and declare the BitmapChanged property type to be EventHandler<YourEventArgsSubclass>

If you have a lot of properties to associate with events, look at implementing INotifyPropertyChanged

Sign up to request clarification or add additional context in comments.

15 Comments

Also instead of using EventHandler<> a delegate can be created to be used for the type of the event, thus it will be strongly typed.
@OlivierRogier: while I don't find this answer to be of much use (there are plenty of duplicates already on the site), I don't understand your critique here. The EventHandler and EventHandler<T> types are both already delegate types. Using either creates just as "strongly typed" an event as using any other delegate type would.
@Olivier Yes, but that is probably only necessary in exceptional circumstances such as when in a context that doesn't understand the generic EventHandler<T> - the documentation outlines that it shouldn't really be necessary to do it so I'm not sure that saying "instead of" is "right", because (to me) it implies a circumstance that is commonly necessary, when it isn't necessary?
What I meant by strongly typed on top of a generic is not a critic but just an alternative meaning that it can sometimes be easier and cleaner to use a dedicated type like for example a MyPropertyChanged delegate instead of a circumstantial Eventhandler<MyArgs>. Otherwise I find the answer adapted and personalized.
Thank you for helping, I will try it out
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.