It's often necessary to prevent some control's event handling when setting is properties in code like check-boxes or radio-buttons etc. To achieve this, I use the following helper:
public static class PropertySetter
{
private static readonly object locker = new object();
public static object CurrentObject { get; private set; }
public static string CurrentPropertyName { get; private set; }
public static void SetValueFor(this object obj, string propertyName, object value)
{
if (obj == null) { throw new ArgumentNullException("obj"); }
if (string.IsNullOrEmpty(propertyName) == true) { throw new ArgumentNullException("'propertyName"); }
PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo == null)
{
throw new ArgumentOutOfRangeException("propertyName", "Property not found.");
}
lock (locker)
{
CurrentObject = obj;
CurrentPropertyName = propertyName;
try
{
propertyInfo.SetValue(obj, value, null);
}
catch (Exception)
{
throw;
}
finally
{
CurrentObject = null;
CurrentPropertyName = null;
}
}
}
public static bool CanHandleEventFor(this object obj, string propertyName)
{
return object.ReferenceEquals(obj, CurrentObject) == false && CurrentPropertyName.Equals(propertyName) == false;
}
}
Usage:
checkBox.SetValueFor("Checked", false);
void checkBox_Checked(object sender, EventArgs e)
{
if (sender.CanHandleEventFor("Checked")) return;
// ...
}
However I thougt perhaps there is a better way without writing the if
inside the event handler but to detach all event handlers for some event by either passing it's name as an additinal parameter or the event field itself and after the property is set reattach them. Is that even possible?