【问题标题】:How do I access a page frame to navigate a page through a UserControl object in a UWP?如何访问页框以通过 UWP 中的 UserControl 对象导航页面?
【发布时间】:2015-11-22 03:49:49
【问题描述】:

我正在使用Windows.UI.Xaml.Navigation 开发一个涉及多个UserControl 对象的UWP 应用程序。

有时,用户应该能够单击这些对象中的按钮以转到新页面。但是,我无法访问页面的框架,因此无法使用以下方法。

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

如何访问页框以使用该方法?

让我知道任何替代方案;我大部分时间都被困在这个问题上!提前感谢你们提供的任何帮助!

【问题讨论】:

    标签: c# wpf xaml uwp


    【解决方案1】:

    我们可以让页面自行导航。只需在您的自定义用户控件中定义一个事件并在其父级(页面)中侦听该事件。

    以以下为例:

    1. 创建一个自定义用户控件并在其上放置一个按钮以进行测试。
    2. 在测试按钮的点击事件中,引发事件以导航父页面。
    3. 在父页面中,监听 UserControl 的事件并调用 Frame.Navigate。

    MyControl 的 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 的 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);
        }
    
    
    }
    

    将 MainPage 导航到 SecondPage:

        public MainPage()
        {
            this.InitializeComponent();
    
            myControl.OnNavigateParentReady += myControl_OnNavigateParentReady;
        }
    
        private void MyControl_OnNavigateParentReady(object source, EventArgs e)
        {
            Frame.Navigate(typeof(SecondPage));
        }
    

    【讨论】:

    • 太棒了!这次真是万分感谢。像魅力一样工作。
    • 我需要将public event 更改为public static event,以便我可以在UserControl 中使用此解决方案,在DataTemplate 中在GridView.ItemTemplate 中在GridView 中在@ 中987654330@ 在Page 内...感谢您提供出色的解决方案。
    • @dav1dsm1th 我有同样的要求。你能详细说明你是如何添加的吗?是在 XAML 中还是在代码后面?
    【解决方案2】:

    您可以从当前窗口的内容中获得对 Frame 的引用。 在您的用户控件代码中尝试:

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

    【讨论】:

      【解决方案3】:

      或者,使用 Cast=>

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

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-07
        相关资源
        最近更新 更多