WPF: Why doesn't PageFunction return to calling Window?

672 views Asked by At

In a WPF Project I am navigating to a PageFunction from a Window using a Frame that is the content of the Window. The trouble is the PageFunction doesn't return back to the calling Window. In fact, calling OnReturn(...) in the PageFunction throws an InvalidOperationException saying:

NavigationWindow of PageFunction was already closed or navigated to different content

Why does the exception get thrown?

Here is some sample code that shows the problem:

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 Code Behind:

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 code behind:

   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"));
    }
}
1

There are 1 answers

0
mm8 On

The window should be a NavigationWindow, i.e. you should change the base type of the MainWindow from Window to NavigationWindow, and the Return event can only be handled the calling page as documented on MSDN: https://msdn.microsoft.com/en-us/library/ms602911%28v=vs.110%29.aspx