WPF User Control Parent

后端 未结 17 1003
不知归路
不知归路 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:47

    Another way:

    var main = App.Current.MainWindow as MainWindow;
    
    0 讨论(0)
  • 2020-11-28 02:49

    I needed to use the Window.GetWindow(this) method within Loaded event handler. In other words, I used both Ian Oakes' answer in combination with Alex's answer to get a user control's parent.

    public MainView()
    {
        InitializeComponent();
    
        this.Loaded += new RoutedEventHandler(MainView_Loaded);
    }
    
    void MainView_Loaded(object sender, RoutedEventArgs e)
    {
        Window parentWindow = Window.GetWindow(this);
    
        ...
    }
    
    0 讨论(0)
  • 2020-11-28 02:50

    I'll add my experience. Although using the Loaded event can do the job, I think it may be more suitable to override the OnInitialized method. Loaded occurs after the window is first displayed. OnInitialized gives you chance to make any changes, for example, add controls to the window before it is rendered.

    0 讨论(0)
  • 2020-11-28 02:51

    If you are finding this question and the VisualTreeHelper isn't working for you or working sporadically, you may need to include LogicalTreeHelper in your algorithm.

    Here is what I am using:

    public static T TryFindParent<T>(DependencyObject current) where T : class
    {
        DependencyObject parent = VisualTreeHelper.GetParent(current);
        if( parent == null )
            parent = LogicalTreeHelper.GetParent(current);
        if( parent == null )
            return null;
    
        if( parent is T )
            return parent as T;
        else
            return TryFindParent<T>(parent);
    }
    
    0 讨论(0)
  • 2020-11-28 02:55

    Different approaches and different strategies. In my case I could not find the window of my dialog either through using VisualTreeHelper or extension methods from Telerik to find parent of given type. Instead, I found my my dialog view which accepts custom injection of contents using Application.Current.Windows.

    public Window GetCurrentWindowOfType<TWindowType>(){
     return Application.Current.Windows.OfType<TWindowType>().FirstOrDefault() as Window;
    }
    
    0 讨论(0)
提交回复
热议问题