I have a user control that I load into a MainWindow
at runtime. I cannot get a handle on the containing window from the UserControl
.
I hav
Gold plated edition of the above (I need a generic function which can infer a Window
within the context of a MarkupExtension
:-
public sealed class MyExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider) =>
new MyWrapper(ResolveRootObject(serviceProvider));
object ResolveRootObject(IServiceProvider serviceProvider) =>
GetService(serviceProvider).RootObject;
}
class MyWrapper
{
object _rootObject;
Window OwnerWindow() => WindowFromRootObject(_rootObject);
static Window WindowFromRootObject(object root) =>
(root as Window) ?? VisualParent((DependencyObject)root);
static T VisualParent(DependencyObject node) where T : class
{
if (node == null)
throw new InvalidOperationException("Could not locate a parent " + typeof(T).Name);
var target = node as T;
if (target != null)
return target;
return VisualParent(VisualTreeHelper.GetParent(node));
}
}
MyWrapper.Owner()
will correctly infer a Window on the following basis:
Window
by walking the visual tree (if used in the context of a UserControl
)Window
's markup)