【问题标题】:Casting exception in the NavigationService在 NavigationService 中投射异常
【发布时间】:2013-12-02 13:53:40
【问题描述】:

我有两个页面(主窗口和客户端),我正在尝试使用 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(),但它给出了同样的例外!

有什么线索吗?

【问题讨论】:

    标签: c# wpf exception casting navigationservice


    【解决方案1】:

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

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

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

    【讨论】:

    • 我应该怎么做才能返回 MainWindow 向客户端发送消息?
    • 有一个问题here 讨论了在 WPF 中的页面之间进行通信的一些更好的方法。
    • 这不是我问先生的!
    • 不,但它是您问题的更好答案。替代方案是:在基类中实现您的MessageFromCallingWindow 属性并让您的所有页面都派生自该属性(意味着您将e.Content 转换为BaseClass 而不是Client),或者您检测页面的类型并适当地投射(例如:if (e.Content is Client) { // do your existing cast } else if (e.Content is MainWindow) { // do a different cast } 等...这不是推荐的方法!
    猜你喜欢
    • 1970-01-01
    • 2018-04-16
    • 2013-08-03
    • 2014-02-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多