WPF User Control Parent

后端 未结 17 1068
不知归路
不知归路 2020-11-28 02:18

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

17条回答
  •  抹茶落季
    2020-11-28 02:36

    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:

    • the root Window by walking the visual tree (if used in the context of a UserControl)
    • the window within which it is used (if it is used in the context of a Window's markup)

提交回复
热议问题