UWP Accessing Frame for page navigation through Usercontrol an Object?

冷暖自知 提交于 2019-12-21 07:21:49

问题


I'm currently developing a UWP application that involves several Usercontrol objects inside of a Map (using Windows.UI.Xaml.Navigation).

with these Usercontrol objects I sometimes require the user to be able to press a button in the objects and be taken to a new page, the only issue is I can't seem to access the page's Frame to be able to use the

Frame.Navigate(typeof([page])); 

method. How would I go about this and/or are there any alternatives? I've been stuck on this most of the day!

Thanks in advance for any help you guys can offer!


回答1:


We can let the page to navigate itself. Just define an event in your custom usercontrol and listen to the event in its parent(the page).

Take the following as an example:

  1. Create a custom user control and put a button on it for test purpose.
  2. In test button's click event, raise the event to navigate parent page.
  3. In Parent page, listen to the UserControl's event and call Frame.Navigate.

MyControl's Xaml:

<UserControl
x:Class="App6.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App6"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <Button x:Name="testbtn" Margin="168,134,0,134" Click="testbtn_Click">test</Button>
</Grid>
</UserControl>

MyControl's CodeBehind:

public sealed partial class MyControl : UserControl
{

    public delegate void MyEventHandler(object source, EventArgs e);

    public event MyEventHandler OnNavigateParentReady;

    public MyControl()
    {
        this.InitializeComponent();
    }

    private void testbtn_Click(object sender, RoutedEventArgs e)
    {
        OnNavigateParentReady(this, null);
    }


}

Navigate MainPage to SecondPage:

    public MainPage()
    {
        this.InitializeComponent();

        myControl.OnNavigateParentReady += myControl_OnNavigateParentReady;
    }

    private void MyControl_OnNavigateParentReady(object source, EventArgs e)
    {
        Frame.Navigate(typeof(SecondPage));
    }



回答2:


You could get a reference to the Frame from the Current Window's Content. In your user control's code behind try:

Frame navigationFrame = Window.Current.Content as Frame;
navigationFrame.Navigate(typeof([page]));



回答3:


Or, with Cast=>

((Frame)Window.Current.Content).Navigate(typeof(Views.SecondPage));



来源:https://stackoverflow.com/questions/32254859/uwp-accessing-frame-for-page-navigation-through-usercontrol-an-object

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