【问题标题】:WPF: Why doesn't PageFunction return to calling Window?WPF:为什么 PageFunction 不返回调用 Window?
【发布时间】:2019-05-24 05:27:34
【问题描述】:

在 WPF 项目中,我使用 Frame(即 Window 的内容)从 Window 导航到 PageFunction。问题是PageFunction 没有返回到调用Window。事实上,在 PageFunction 中调用 OnReturn(...) 会引发 InvalidOperationException 说:

PageFunction 的NavigationWindow 已经关闭或导航到不同的内容

为什么会抛出异常?

下面是一些显示问题的示例代码:

MainWindow.xaml

<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication3"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Frame x:Name="frame" />

MainWindow 后面的代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var myPageFunction = new MyPageFunction();

        myPageFunction.Return += MyPageFunction_Return;
        frame.Navigate(myPageFunction);

    }

    private void MyPageFunction_Return(object sender, ReturnEventArgs<string> e)
    {
        // Doesn't get here!
    }
}

PageFunction.xaml

<PageFunction
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib" 
x:Class="WpfApplication3.MyPageFunction"
x:TypeArguments="sys:String"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication3"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="MyPageFunction">
<Grid>
    <Button x:Name="btnReturn" Click="btnReturn_Click" Content="Return"/>
</Grid></PageFunction>

后面的PageFunction代码:

   public partial class MyPageFunction : PageFunction<String>
{
    public MyPageFunction()
    {
        InitializeComponent();
    }

    private void btnReturn_Click(object sender, RoutedEventArgs e)
    {
        // THIS THROWS EXCEPTION!
        OnReturn(new ReturnEventArgs<string>("return"));
    }
}

【问题讨论】:

    标签: c# wpf xaml pagefunction


    【解决方案1】:

    窗口应该是 NavigationWindow,即您应该将 MainWindow 的基本类型从 Window 更改为 NavigationWindow,并且 Return 事件只能处理调用 page,如 MSDN 中所述:@987654321 @

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多