侧边栏壁纸
博主头像
Tony's Blog博主等级

行动起来,coding

  • 累计撰写 83 篇文章
  • 累计创建 58 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
c#

.Net6 WPF 报错:不具有由 URI“xxx”识别的资源

Tony
2024-02-17 / 0 评论 / 0 点赞 / 11 阅读 / 3815 字

本文链接: https://blog.csdn.net/lishuangquan1987/article/details/125020580

版权

跟之前的文章一样

在做WPF开发的时候,经常遇到如下错误: 不具有由 URI“xxx”识别的资源 或者 The component ‘XXX’ does not have a resource identified by the URI

1-xhjw.png

根本原因暂未找到。但是可以通过如下办法解决:

有哪位大神找打根本原因,欢迎留言给我,不胜感激

新建一个View的拓展方法:

public static class Extension
{
    /// <summary>
    /// wpf 出现 组件“xxx”不具有由 URI“xxx”识别的资源。错误时的解决办法
    /// </summary>
    /// <param name="userControl"></param>
    /// <param name="baseUri"></param>
    public static void LoadViewFromUri(this FrameworkElement userControl, string baseUri)
    {
        try
        {
            var resourceLocater = new Uri(baseUri, UriKind.Relative);
            var exprCa = (PackagePart)typeof(System.Windows.Application).GetMethod("GetResourceOrContentPart", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { resourceLocater });
            var stream = exprCa.GetStream();
            var uri = new Uri((Uri)typeof(BaseUriHelper).GetProperty("PackAppBaseUri", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null, null), resourceLocater);
            var parserContext = new ParserContext
            {
                BaseUri = uri
            };
            typeof(XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { stream, parserContext, userControl, true });
        }
        catch (Exception)
        {
            //log
        }
    }
}

在View的构造函数中注释掉 InitializeComponent 方法,使用拓展方法:

public LoginView(IContainerProvider container)
{
 	 //InitializeComponent(); //注释掉
     this.LoadViewFromUri("/Test.ClientUI;component/Views/LoginView.xaml");
     this.DataContext = container.Resolve<LoginViewModel>((typeof(LoginView),this));
}

问题追踪:

https://github.com/dotnet/wpf/issues/4494

https://github.com/dotnet/wpf/issues/1700

0

评论区