WPFUI報錯 - page does not have a parameterless constructor

来源:https://www.cnblogs.com/louzixl/p/18346088
-Advertisement-
Play Games

WPFUI報錯 page does not have a parameterless constructor. If you are using Wpf.Ui.IPageService do not navigate initially and don't use Cache or Precache ...


WPFUI報錯

page does not have a parameterless constructor. If you are using Wpf.Ui.IPageService do not navigate initially and don't use Cache or Precache

問題原因

WPFUI中的NavigationView只支持導航頁面的無參構造函數或含一個dataContext的有參構造函數。因為在View的構造函數中註入了一些服務,導致View創建失敗,WPFUI報錯。

問題處理

查看異常堆棧,找報錯位置:

在 Wpf.Ui.Controls.NavigationViewActivator.CreateInstance(Type pageType, Object dataContext) 在 Wpf.Ui.Controls\NavigationViewActivator.cs 中: 第 37 行
在 Wpf.Ui.Controls.NavigationView.GetPageInstanceFromCache(Type targetPageType) 在 Wpf.Ui.Controls\NavigationView.cs 中: 第 1206 行
在 Wpf.Ui.Controls.NavigationCache.Remember(Type entryType, NavigationCacheMode cacheMode, Func`1 generate) 在 Wpf.Ui.Controls\NavigationCache.cs 中: 第 25 行
在 Wpf.Ui.Controls.NavigationView.GetNavigationItemInstance(INavigationViewItem viewItem) 在 Wpf.Ui.Controls\NavigationView.cs 中: 第 1185 行
在 Wpf.Ui.Controls.NavigationView.NavigateInternal(INavigationViewItem viewItem, Object dataContext, Boolean addToNavigationStack, Boolean isBackwardsNavigated) 在 Wpf.Ui.Controls\NavigationView.cs 中: 第 1131 行
在 Wpf.Ui.Controls.NavigationViewItem.OnClick() 在 Wpf.Ui.Controls\NavigationViewItem.cs 中: 第 314 行
...

看源碼,找解決方案:

private object GetNavigationItemInstance(INavigationViewItem viewItem)
{
    if (viewItem.TargetPageType is null)
    {
        throw new InvalidOperationException(
            $"The {nameof(viewItem)}.{nameof(viewItem.TargetPageType)} property cannot be null."
        );
    }

    if (_serviceProvider is not null)
    {
        return _serviceProvider.GetService(viewItem.TargetPageType)
            ?? throw new InvalidOperationException(
                $"{nameof(_serviceProvider)}.{nameof(_serviceProvider.GetService)} returned null for type {viewItem.TargetPageType}."
            );
    }

    if (_pageService is not null)
    {
        return _pageService.GetPage(viewItem.TargetPageType)
            ?? throw new InvalidOperationException(
                $"{nameof(_pageService)}.{nameof(_pageService.GetPage)} returned null for type {viewItem.TargetPageType}."
            );
    }

    return _cache.Remember(
            viewItem.TargetPageType,
            viewItem.NavigationCacheMode,
            ComputeCachedNavigationInstance
        )
        ?? throw new InvalidOperationException(
            $"Unable to get or create instance of {viewItem.TargetPageType} from cache."
        );

    object? ComputeCachedNavigationInstance() => GetPageInstanceFromCache(viewItem.TargetPageType);
}

可以看到,如果提供了serviceProvider或者pageService,就可以通過容器獲取View實例,不需要通過NavigationViewActivator.CreateInstance創建實例了。

提供ServiceProvider,例如使用Prism:

public class PrismServiceProvider : IServiceProvider
{
    private readonly IContainerProvider _containerProvider;

    public PrismServiceProvider(IContainerProvider containerProvider)
    {
        _containerProvider = containerProvider;
    }

    public object GetService(Type serviceType)
    {
        return _containerProvider.Resolve(serviceType);
    }
}

WPFUI中未提供預設的IPageService實現,但demo.mvvm中提供了基於IServiceProvider的實現,可以參考。本文基於Prism實現:

public class PageService : IPageService
{
    private readonly IContainerProvider _containerProvider;

    public PageService(IContainerProvider containerProvider)
    {
        _containerProvider = containerProvider;
    }

    public T GetPage<T>() where T : class
    {
        if (!typeof(FrameworkElement).IsAssignableFrom(typeof(T)))
            throw new InvalidOperationException("The page should be a WPF control.");

        return (T)_containerProvider.Resolve(typeof(T));
    }

    public FrameworkElement GetPage(Type pageType)
    {
        if (!typeof(FrameworkElement).IsAssignableFrom(pageType))
            throw new InvalidOperationException("The page should be a WPF control.");

        return _containerProvider.Resolve(pageType) as FrameworkElement;
    }
}

最後一步,將PrismServiceProvider、PageService註入容器,並通過INavigationService為NavigationView設置IServiceProvider和IPageService:

// App.xaml.cs
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    var serviceProvider = new PrismServiceProvider(Container);
    containerRegistry.RegisterInstance<IServiceProvider>(serviceProvider);
    containerRegistry.RegisterSingleton<IPageService, PageService>();
    containerRegistry.RegisterSingleton<INavigationService, NavigationService>();
}

// MainWindow.xaml.cs
public MainWindow(INavigationService navigationService,
    IPageService pageService,
    ISnackbarService snackbarService)
{
    InitializeComponent();

    navigationService.SetPageService(pageService);
    navigationService.SetNavigationControl(NavigationView);
}
轉載請註明出處,歡迎交流。
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 視窗/屏幕截圖適用於截圖、批註等工具場景,時時獲取視窗/屏幕圖像數據流呢,下麵講下視頻會議共用桌面、遠程桌面這些場景是如何實現畫面錄製的。 常見的屏幕畫面時時採集方案,主要有GDI、WGC、DXGI。 GDI GDI(Graphics Device Interface)就是使用user32下Wind ...
  • 前言 基於 .NET 8 的開源項目,主要使用 WebAPI + Blazor 支持多租戶和模塊化設計,DDD構建。可以幫助我們輕鬆地搭建起一個功能完善的Web應用程式。除了幫助你快速構建應用程式之外,項目也可以當做學習資料。我們可以從中瞭解到多租戶、CQRS、DDD架構、雲部署、Docker容器化 ...
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他們的程式崩潰了,也自己分析了下初步結果,讓我幫忙再確認下,既然讓我確認,那就開始dump分析之旅吧。 二:WinDbg 分析 1. 為什麼會崩潰 windbg 有一個強大之處就是帶有一個自動化的分析命令 !analyze -v 可以幫助我們快速的分析 ...
  • 前言 WaterCloud 是一個集成了 LayUI 的高效敏捷開發框架,專為 .NET 開發者設計。 它不僅支持多種 .NET 版本(.NET 4.5、.NET Core 3.1、.NET 5、.NET 6),還內置了豐富的功能,如許可權管理、流程表單設計以及多資料庫支持下的多租戶架構。使用了 OR ...
  • 一:背景 1. 講故事 前些天有位朋友找到我,說他們的系統出現了CPU 100%的情況,讓我幫忙看一下怎麼回事?dump也拿到了,本想著這種情況讓他多抓幾個,既然有了就拿現有的分析吧。 二:WinDbg 分析 1. 為什麼會爆高 既然說是 100%,作為調試者得拿數據說話,可以使用 !tp 來觀測一 ...
  • Docker部署.netCore6 第一步:在項目添加Docker支持 第二步:選擇Windows(如果是linx系統就選擇linx)和Dockerfile 第三步:生成Docker預設文件 把預設代碼修改 第四步:修改Dockerfile文件屬性(如果不修改則會導致發佈的時候Docker文件沒有一 ...
  • 項目使用ABP框架,最近有需求數據量會持續變大,需要分表存儲。 發現ShardinfCore可以快速實現EF分表操作,並且作者@薛家明還特別為ABP集成寫了教程,完美的選擇。 ShardinfCore作者教程很齊全,這次以ABP 8.*的用戶視角進行集成記錄,希望幫到需要的人。 開發環境: ABP ...
  • IoTClient 是一個針對物聯網 (IoT) 領域的開源客戶端庫,它主要用於實現與各種工業設備之間的通信。這個庫是用 C# 編寫的,並且基於 .NET Standard 2.0,這意味著可以用於多個版本的.NET,包括 .NET Framework、.NET Core、.NET 5 及以上版本,... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...