wpf 如何点击页面的一个按钮来改变Windows的框架来源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29297986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:02:48  来源:igfitidea点击:

How to click a button of the page to change the source of the frame of Windows?

wpfframe

提问by zhchma

I have a WPF project, I add a frame in the Windows,the source of the frame is the page. I want to achieve clicking a button in the page to change the page of the frame.

我有一个WPF项目,我在Windows中添加了一个框架,框架的来源是页面。我想实现点击页面中的一个按钮来改变框架的页面。

<Window x:Class="MagicArm.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MagicArm"
    Title="MainWindow">
   <Frame Name="FrameContent"Source="PageStart.xaml"></Frame>
</Window>

PageStart:

页面开始:

<Page x:Class="MagicArm.PageStart"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d" 
  Height="452" Width="800"
  Title="PageStart">
<Canvas>
 <button name=""> </button>
</Canvas>

回答by Dragos Stoica

EDIT: A functional solution can look like:

编辑:功能性解决方案可能如下所示:

MainWindow XAML:

主窗口 XAML:

<StackPanel>
    <Frame Name="frmMainContent" Height="260"
         DataContext="MyPageInformation"
         Source="{Binding}"
         NavigationUIVisibility="Hidden">           
    </Frame>

</StackPanel>

MainWindow cs:

主窗口 cs:

 frmMainContent.Source = new Uri("test1.xaml", UriKind.Relative); // initialize frame with the "test1" view

test1 XAML:

测试 1 XAML:

<Grid>
    <Button Click="ButtonBase_OnClick" Background="Red" Height="30" Width="100">Go to page 2</Button>
</Grid>

test1 cs:

测试1 cs:

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        NavigationService ns = NavigationService.GetNavigationService(this);
        ns.Navigate(new Uri("test2.xaml", UriKind.Relative));
    }

test2 XAML:

测试2 XAML:

  <Grid>
        <Button Click="ButtonBase_OnClick" Width="100" Height="30" Background="RoyalBlue"> Go to page 1</Button>
    </Grid>

test2 cs:

测试2 cs:

 NavigationService ns = NavigationService.GetNavigationService(this);
            ns.Navigate(new Uri("test1.xaml", UriKind.Relative));

This is a working solution using NavigationService.

这是使用 NavigationService 的有效解决方案。