Назад навигация по кадрам в приложении UWP - PullRequest
0 голосов
/ 16 октября 2018

У меня есть приложение UWP, которое имеет 3 страницы, а третья страница содержит тег кадра, который загружает несколько кадров.Допустим, я перехожу к странице 1-> странице 2-> Страница 3-> Кадр 1-> Кадр 2-> Кадр 3. Если я нажимаю кнопку «Назад» из кадров 3 и 2, она переходит на страницу 2 вместо кадра 2 и кадра 1соответственно.У меня есть общий метод для обработки события кнопки «Назад», и он берет корневой фрейм, который одинаков для фреймов 1,2 и 3, который является страницей 3, и возвращается на свою предыдущую страницу 2. Так, как я могу вместо этого вернуться к фреймам?корневой страницы назад.Ниже приведен общий метод back, который у меня есть в App.xaml.cs.Пожалуйста, помогите.

  protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        Windows.UI.Core.SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;

        }
    }


    private void App_BackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
    {
        e.Handled = On_BackRequested();
    }



    private bool On_BackRequested()
    {
        Frame rootFrame = Window.Current.Content as Frame;



        if (rootFrame.CanGoBack)
        {
            rootFrame.GoBack();
            return true;
        }
        return false;
    }

public HomeView()
    {
        this.InitializeComponent();
        var vm = new HomeViewModel(new UserService(), new SubscriptionService(), new TransactionService(),new GameService());
        this.DataContext = vm;
        WalletBtn.Foreground = new SolidColorBrush(Colors.White);
        PaymentGrid = BuyModal;
        //PowerPassGameListGrid = PowerPassGameGrid;
       // SystemNavigationManager.GetForCurrentView().BackRequested += HomePage_BackRequested;
        PointBalance = wallet;
        //QueuedGames = QueueGame;
        //PowerPassSubscriptionGrid = PowerPass;
        SubmitPopUp = SuccessPopUp;
        RecentActivityGrid = RecentActivityModel;
        CurrentlyPickedPopUp = GamePickUp;
        PowerUpNavigationGrid = NavigationGrid;
    }
    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        string firstName = (string)ApplicationData.Current.LocalSettings.Values["FirstName"];
        string lastName = (string)ApplicationData.Current.LocalSettings.Values["LastName"];
        if (firstName != null && lastName != null)
        {
            welcomeMessage.Text = "Hi, " + firstName;
        }
    }
    public void MyWalletButton_Click(object sender, RoutedEventArgs e)
    {
        PowerPassBtn.Foreground = new SolidColorBrush(Colors.Gray);
        WalletBtn.Foreground = new SolidColorBrush(Colors.White);       
    }
    public void PowerPassButton_Click(object sender, RoutedEventArgs e)
    {
        PowerPassSelection();
    }

    //private void HomePage_BackRequested(object sender, BackRequestedEventArgs e)
    //{
    //    e.Handled = true;
    //    this.Frame.Navigate(typeof(LoginUsernameView));
    //}
    private void ButtonGotFocus(object sender, RoutedEventArgs e)
    {
        (sender as Button).Background = new SolidColorBrush(Colors.Green);
    }

    private void ButtonLostFocus(object sender, RoutedEventArgs e)
    {
        (sender as Button).Background = new SolidColorBrush(Colors.Transparent);
    }

    private void QueueButtonGotFocus(object sender, RoutedEventArgs e)
    {
        (sender as Button).Background = new SolidColorBrush(Colors.DeepSkyBlue);
    }

    private void QueueButtonLostFocus(object sender, RoutedEventArgs e)
    {
        (sender as Button).Background = new SolidColorBrush(Colors.Transparent);
    }

    private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
    {
        var parent = VisualTreeHelper.GetParent(dependencyObject);
        if (parent == null) return null;

        var parentT = parent as T;
        return parentT ?? FindParent<T>(parent);
    }
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        NavigationParameterDTO parameter = e.Parameter as NavigationParameterDTO;
        if (parameter != null)
        {
            if (parameter.FrameName == "WelcomeView")
            {
                HomeViewModel vm = this.DataContext as HomeViewModel;
                vm.PowerPassWelcomeFrame.Execute(null);
                PowerPassSelection();
            }
            else if(parameter.FrameName == "CheckOut")
            {
                HomeViewModel vm = this.DataContext as HomeViewModel;
                vm.PowerPassGameCheckOutMethod.Execute(null);
                PowerPassSelection();
            }
            else if(parameter.FrameName== "SignUp")
            {
                HomeViewModel vm = this.DataContext as HomeViewModel;
                vm.PowerPassFrame.Execute(null);
                PowerPassSelection();
            }
            else
            {
                HomeViewModel vm = this.DataContext as HomeViewModel;
                vm.PowerPassHomeFrame.Execute(null);
                PowerPassSelection();
            }
        }
    }

Xaml

                   <Button Style="{StaticResource PowerUpButtonStyle}"  x:Uid="Profile"  FontSize="36" Margin="0,60,0,0" Name="SettingsBtn" XYFocusDown="{x:Bind SettingsBtn}" FontFamily="Segoe Pro" Foreground="Gray" FocusVisualPrimaryThickness="0,0,0,3" FocusVisualMargin="10,0">
                        <Button.Background>
                            <SolidColorBrush Opacity="0"/>
                        </Button.Background>
                        <Button.Resources>
                            <ResourceDictionary>
                                <ResourceDictionary.ThemeDictionaries>
                                    <ResourceDictionary x:Key="Light">
                                        <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="White"/>
                                    </ResourceDictionary>
                                </ResourceDictionary.ThemeDictionaries>
                            </ResourceDictionary>
                        </Button.Resources>
                    </Button>
                </StackPanel>
                <Image Source="/Assets/Images/PURlogo_large.png" HorizontalAlignment="Left"  Margin="70,950" Width="212" Height="78"/>
            </Grid>
        </StackPanel>
        <Frame x:Name="MainFrame" Grid.Column="1" Content="{Binding FrameData,Mode=OneWay}" >
        </Frame>
        <Grid Background="Red" Visibility="Collapsed" x:Name="testgrid">
            <TextBlock Text="hello world"></TextBlock>
        </Grid>
    </Grid>

1 Ответ

0 голосов
/ 16 октября 2018

Использование Window.Current.Content дает вам самый корень Frame приложения.Если вы хотите проверить, открыт ли в данный момент Page3, и использовать его фреймы, вам нужно будет сделать что-то вроде:

private bool On_BackRequested()
{
    Frame rootFrame = Window.Current.Content as Frame;

    if (rootFrame.Content is Page3 page3 )
    {
         var innerFrame = page3.GetInnerFrame(); //implement this method in Page3
         if (innerFrame.CanGoBack)
         {
             innerFrame.GoBack();
             return true;
         }
    } 

    if (rootFrame.CanGoBack)
    {
        rootFrame.GoBack();
        return true;
    }
    return false;
}

Метод GetInnerFrame будет в Page3 code-behind ипросто вернет фрейм, который находится на странице.

Приведенный выше код просто вернется назад с фреймом, который находится внутри Page3.Если вы продолжите вложение, вам снова придется работать с Content этого кадра и т. Д.

...