Accessing MainWindow's controls from a user control page. WPF C#

二次信任 提交于 2019-12-23 13:20:53

问题


I have a page transition ( a control ) in the MainWindow , I have many user control pages , I want to access the page transition in the MainWindow from my user control page ? How do I do that? I tried :

        Story page = new Story();
        NavigationService nav = NavigationService.GetNavigationService(this);
        // Navigate to the page, using the NavigationService
      //  if (nav != null)
       // { 
        //    nav.Navigate(page);
            MainWindow test = new MainWindow();
            test.pageTransition1.ShowPage(page);

    //    }

回答1:


Application.Current.MainWindow

Using this you can access the MainWindow from any place.




回答2:


You could find the WpfPageTransitions.PageTransition control like this from the UserControls code behind:

public static WpfPageTransitions.PageTransition FindPageControl(DependencyObject child)
{
    DependencyObject parent= VisualTreeHelper.GetParent(child);

    if (parent == null) return null;

    WpfPageTransitions.PageTransition page = parent as WpfPageTransitions.PageTransition;
    if (page != null)
    {
        return page;
    }
    else
    {
        return FindPageControl(parent);
    }
}

Then you can use it like this:

this.FindPageControl(this).ShowPage(...);



回答3:


Create A Method Inside Main Window for Choosing Page Transition

 public   void ChangePage()
        {
            pageTransitionControl.ShowPage(new NewData());
        }

Then in Child control

private void btnUpdate_Click(object sender,RoutedEventArgs e)
        {

            MainWindow win = (MainWindow)Window.GetWindow(this);
            win.ChangePage();
        }


来源:https://stackoverflow.com/questions/17562358/accessing-mainwindows-controls-from-a-user-control-page-wpf-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!