You need to enable JavaScript to run this app. WPF中使用ReactiveUI时RoutedViewHost无法解析StartupViewModel视图
优惠活动
大模型
产品
解决方案
定价
更多

WPF中使用ReactiveUI时RoutedViewHost无法解析StartupViewModel视图

问题原因

该异常是ReactiveUI的视图定位器未找到StartupViewModel对应的视图导致的,你的代码命名符合ReactiveUI默认的视图-ViewModel匹配规则(XXXViewModel对应XXXView),问题出在没有完成视图映射注册。

解决步骤

1. 检查StartupView后置代码继承关系

确认StartupView.xaml.cs的类继承不是默认的UserControl,必须显式继承ReactiveUserControl<StartupViewModel>,示例代码如下:

using ReactiveUI;
using LearnReactiveUI.ViewModels;

namespace LearnReactiveUI.Views
{
    [ViewFor(typeof(StartupViewModel))] // 可选,显式标记映射关系
    public partial class StartupView : ReactiveUserControl<StartupViewModel>
    {
        public StartupView()
        {
            InitializeComponent();
        }
    }
}

2. 程序启动时注册视图映射

在项目的App.xaml.cs中重写OnStartup方法,扫描当前程序集完成所有视图与ViewModel的映射注册:

using ReactiveUI;
using System.Reflection;
using System.Windows;

namespace LearnReactiveUI
{
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            // 注册当前程序集中所有符合命名规则的视图-ViewModel映射
            Locator.CurrentMutable.RegisterViewsForViewModels(Assembly.GetExecutingAssembly());
        }
    }
}

完成以上两步后重新运行项目即可正常加载StartupView。

内容的提问来源于stack exchange,提问作者KosherMeatBoy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 02:09:01