vendredi 30 janvier 2015

Sending a method as a parameter via reflection for registering a callback

Is there a way for me to call a method via reflection with a parameter being another method?



private void CalendarPopup_Opened(object sender, EventArgs e)
{
var parent = GetParent(CalendarPopup, typeof(Popup));
if (parent != null)
{
object parentWindow = Window.GetWindow(CalendarPopup);
Type parentWindowType = parentWindow.GetType();

var methodInfo = parentWindowType.GetMethod("RegisterMouseDownCallback");
if (methodInfo != null)
{
object[] parameters = new object[1];
//************************
parameters[0] = PopupCallback; //Problem here
//************************
methodInfo.Invoke(parentWindow, parameters);
}
}
}

private void PopupCallback(object sender, MouseButtonEventArgs args)
{
var obj = args.Source;
if (obj != null)
{
var parent = GetParent(obj as DependencyObject, typeof(Popup));
if (parent != null && !parent.Equals(CalendarPopup))
{
this.CalendarPopup.IsOpen = false;
}
}
}


The above code belongs to a UserControl which is actually loaded via reflection, so, neither the UserControl or Window which houses RegisterMouseDownCallback know much about each other.


This is the code for the RegisterMouseDownCallback in the window:



private IList<MetroWindowMouseDownCallback> callbacks = new List<MainWindowMouseDownCallback>();

public delegate void MetroWindowMouseDownCallback(object sender, MouseButtonEventArgs args);

public MetroWindow() : base()
{
PreviewMouseUp += MetroWindow_MouseUp;
}

public void RegisterMouseDownCallback(MetroWindowMouseDownCallback callback)
{
callbacks.Add(callback);
}

public void UnRegisterMouseDownCallback(MetroWindowMouseDownCallback callback)
{
if (callbacks.Contains(callback))
callbacks.Remove(callback);
}

void MetroWindow_MouseUp(object sender, MouseButtonEventArgs e)
{
foreach (var callback in callbacks)
callback.Invoke(sender, e);
}





Aucun commentaire:

Enregistrer un commentaire