-1

我有两个页面(MainWindow 和客户端),我正在尝试使用 NavigationService 在我的页面之间导航。

当我从 MainWindow 导航到 Client 时,它可以工作,但是当我尝试从 Client 导航到 MainWindow 时,它给了我一个异常:

无法将 WpfApplication1.MainWindow 类型的对象转换为 WpfApplication1.Client

这是我的主窗口

<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;
}

和客户端

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

我也试过NaviugationService.GoBack()了,但它给出了同样的例外!

有什么线索吗?

4

1 回答 1

1

每次导航完成时,您都会调用此代码:

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

很简单,当您导航到 时,该代码将失败,MainWindow因为您无法将其转换为Client.

于 2013-12-02T14:01:15.447 回答