I have implemented an extension helper to load a WPF usercontrol to a window dynamically. (MyButton is in another assembly).
This helper is in a class lib that is used in all my projects. The idea is to save on re-coding this operation and keep the client code cleaner.
I would like a second pair of eyes (or more) to let me know if the cost of this to too high.
Thanks.
public static Window OpenUserControl(this MyButton button, string controlName, string title)
{
//
object uControl;
try
{
Type newType = button.GetType().Assembly.GetType(controlName,true,true);
uControl = Activator.CreateInstance(newType);
}
catch (Exception e)
{
throw;
}
// launch the usercontrol as a window.
Window form = new Window
{
Title = title,
Content = uControl,
ShowInTaskbar = false
};
return form;
}
If you know the type at compile-time, you'd be a lot better off making this generic:
// Possibly add more generic constraints to T?
public static Window OpenUserControl<T>(string title)
where T : new()
{
return new Window
{
Title = title,
Content = new T(),
ShowInTaskbar = false
};
}
This is likely to be a bit faster than finding the type by reflection, although another option would be to cache a delegate to call the parameterless constructor - more work, but much faster in my experience. You could do that via a nested generic class, caching a Func<T>
or Func<object>
in the class as a static field.
Only you can really tell whether this is fast enough - but it should be easy enough to benchmark, and I very much doubt that it's going to be a bottleneck.
See more on this question at Stackoverflow