Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a notify method to fire the PropertyChanged event.
private MethodDefinition CreateNotificationMethodDefinition()
{
const string MethodName = "NotifyViewableProperty";
var methodDef = new MethodDefinition(MethodName,
MethodAttributes.Private |
MethodAttributes.HideBySig,
this._types.Void);
var paramDef = new ParameterDefinition("propertyName",
ParameterAttributes.None,
_types.String);
methodDef.Parameters.Add(paramDef);
methodDef.Body.MaxStackSize = 4;
var v = new VariableDefinition(_types.PropertyChangedEventHandler);
methodDef.Body.Variables.Add(v);
methodDef.Body.InitLocals = true;
var il = methodDef.Body.GetILProcessor();
Action<OpCode> op = x => il.Append(il.Create(x));
// IL_0000: ldarg.0
op(OpCodes.Ldarg_0);
// IL_0001: ldfld class [System]System.ComponentModel.PropertyChangedEventHandler Voodoo.ViewModel.GoalViewModel::PropertyChanged
var eventHandlerFieldDef = FindEventFieldDeclaration(_typeDef);
il.Append(il.Create(OpCodes.Ldfld, eventHandlerFieldDef));
// IL_0006: stloc.0
op(OpCodes.Stloc_0);
// IL_0007: ldloc.0
op(OpCodes.Ldloc_0);
//IL_0008: brfalse.s IL_0017
var jumpTargetInsn = il.Create(OpCodes.Ret); // See below, IL_0017
il.Append(il.Create(OpCodes.Brfalse_S, jumpTargetInsn));
// IL_000a: ldloc.0
op(OpCodes.Ldloc_0);
// IL_000b: ldarg.0
op(OpCodes.Ldarg_0);
// IL_000c: ldarg.1
op(OpCodes.Ldarg_1);
// IL_000d: newobj instance void [System]System.ComponentModel.PropertyChangedEventArgs::.ctor(string)
var eventArgsTypeRef = _types.PropertyChangedEventArgs;
var ctorRef = new MethodReference(".ctor",
_types.Void,
eventArgsTypeRef);
var ctorParamDef = new ParameterDefinition("propertyName",
ParameterAttributes.None,
_types.String);
ctorRef.Parameters.Add(ctorParamDef);
ctorRef.HasThis = true;
il.Append(il.Create(OpCodes.Newobj, ctorRef));
// IL_0012: callvirt instance void [System]System.ComponentModel.PropertyChangedEventHandler::Invoke(object, class [System]System.ComponentModel.PropertyChangedEventArgs)
var invokeMethodRef = new MethodReference("Invoke",
_types.Void,
_types.PropertyChangedEventHandler);
invokeMethodRef.Parameters.Add(
new ParameterDefinition(_types.Object));
invokeMethodRef.Parameters.Add(
new ParameterDefinition(eventArgsTypeRef));
invokeMethodRef.HasThis = true;
il.Append(il.Create(OpCodes.Callvirt, invokeMethodRef));
// IL_0017: ret
il.Append(jumpTargetInsn);
return methodDef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment