Firing an event with a class property

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to fire an event within the property of a class. Here's an example:

private bool _canprint;
public bool CanPrint
{
get
{
return _canprint;
}
set
{
_canprint = value;

try
{
if (ModelEvent != null)
{
//ModelEvent(this, new EventArgs());
//ModelEvent("CanPrint", new EventArgs());
}
}
catch
{
// Handle exceptions
}
}
}


Originally I used the "this" keyword, as I had seen elsewhere. But this
just passes the instantiation of the class and not the property itself. The
problem is that I don't know precisely which Property is firing the event.
So I thought about just changing it to a string but that seems less than
elegant.

Hoping someone can suggest how I can pass a reference to the property itself.

Robert W.
MWTech
Vancouver, BC
 
I just discovered something new:

By declaring "using System.Reflection;" I could then fire the event this way:

Type modelType = this.GetType();
PropertyInfo property = modelType.GetProperty("CanPrint");
ModelEvent(property, new EventArgs());


But it seems weird to me to be using System Reflection WITHIN the class
itself.

Hoping someone can either confirm I'm taking the right approach or show me a
better way.

Robert
 
Robert W. said:
I want to fire an event within the property of a class. Here's an example:

Hoping someone can suggest how I can pass a reference to the property
itself.

What do you mean by "the property itself"? The property is just a pair
of methods, effectively. If you want the *value* of the property, just
use it as you would anywhere else. What are you really trying to pass
to ModelEvent?
 
Jon,

Thank you for replying. I'm sorry that I didn't explain mysef clearly. I'm
still learning; learning quickly, but still learning!

To answer your question, it was actually a reference to the Property itself
that I was looking for - ie. the entire structure including:
- The Property's type
- The GetValue method
- The SetValue method

As these things often go, I eventually found a simple way to do this. I
just unboxed the "sender" object as follows:

PropertyInfo propInfo = (PropertyInfo) sender;

This provided me exactly the information I needed. With the propInfo
variable I could then access every aspect of the Property.

But thank you again,

Robert W.
MWTech
Vancouver, BC
 
Back
Top