Casting exception in the NavigationService

241 views Asked by At

I have two Pages (MainWindow & Client) and I'm trying to use the NavigationService to navigate between my pages.

When I navigate from MainWindow to the Client it works, but when I try to navigate from the Client to the MainWindow it gives me an exception :

Cannot cast object of type WpfApplication1.MainWindow to WpfApplication1.Client

This is my MainWindow

<Grid>
    <Button HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Click="Navigate_Click">Navigate</Button>
</Grid>

private void Navigate_Click(object sender, RoutedEventArgs e)
{
    if (NavigationService == null)
    {
        return;
    }

    NavigationService.Navigate(new Uri("Client.xaml", UriKind.Relative), "Hi from calling window!");
    NavigationService.LoadCompleted += NavigationService_LoadCompleted;
}

private void NavigationService_LoadCompleted(object sender, NavigationEventArgs e)
{
    ((Client)e.Content).MessageFromCallingWindow = (string)e.ExtraData;
}

And the client

<Grid>
    <StackPanel>
        <TextBlock VerticalAlignment="Center"
                   HorizontalAlignment="Center"
                   Text="{Binding MessageFromCallingWindow}" />

        <Button Click="OnClick">Go back</Button>
    </StackPanel>
</Grid>

public static DependencyProperty MessageFromCallingWindowProperty = DependencyProperty.Register("MessageFromCallingWindow", typeof(string), typeof(Client));

public string MessageFromCallingWindow
{
    get { return (string)GetValue(MessageFromCallingWindowProperty); }
    set { SetValue(MessageFromCallingWindowProperty, value); }
}

private void OnClick(object sender, RoutedEventArgs e)
{
    if (NavigationService != null)
    {
        NavigationService.Navigate(new Uri("MainWindow.xaml", UriKind.Relative), "returning hello from client");
    }
}

I tried also NaviugationService.GoBack(), but it gives the same exception !

Any clue ?

1

There are 1 answers

4
Dan Puzey On BEST ANSWER

Every time your navigation completes you call this code:

((Client)e.Content).MessageFromCallingWindow = (string)e.ExtraData;

Quite simply, that code will fail when you navigate to the MainWindow because you can't cast it to Client.