【问题标题】:ResourceDictionary creation through code in WPF通过 WPF 中的代码创建 ResourceDictionary
【发布时间】:2020-09-21 21:41:55
【问题描述】:

我有一个 WPF 用户控件项目,我正在尝试使用以下代码创建资源字典

var resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri("/SampleExtension;component/MyResource.xaml", UriKind.Relative);

上面的代码抛出 NotSupportedException 并显示消息“无法识别 URI 前缀”。顺便说一句,MyResource.xaml 的构建操作设置为 Resource。

从 XAML 中使用的类似 URI 可以完美运行。

<UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="/SampleExtension;component/MyResource.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <my:ViewModel x:Key="ViewModel"/>
    </ResourceDictionary>
</UserControl.Resources>

我在代码中做错了什么?

【问题讨论】:

    标签: c# wpf xaml


    【解决方案1】:

    您可能缺少授权路径。 应该是;

     "pack://application:,,,/SampleExtension;component/MyResource.xaml" 
    

    供您参考: https://msdn.microsoft.com/en-us/library/aa970069(v=vs.110).aspx

    希望对您有所帮助。

    【讨论】:

    • 我添加了一条评论作为单独的答案,因为这里的格式丢失了......
    【解决方案2】:

    由于我的项目是一个用户控制项目(当我测试上面的代码时 WPF 应用程序没有运行),我将不得不引用 Application 类。

    var app = Application.Current;
    var resourceDictionary = new ResourceDictionary();
    resourceDictionary.Source = new Uri("/SampleExtension;component/MyResource.xaml", UriKind.RelativeOrAbsolute);
    

    question中已经解释了类似的东西

    【讨论】:

      【解决方案3】:

      从 HungDL 的链接中它还指出:

      来自同一个链接:

      完全限定的包 URI 包括方案、权限和 路径,它被认为是一个绝对的包 URI。作为简化 对于开发人员,XAML 元素通常允许您设置适当的 具有相对包 URI 的属性,其中仅包含路径。

      例如,考虑以下资源的绝对包 URI 本地程序集中的文件。

      pack://application:,,,/ResourceFile.xaml

      引用此资源文件的相对包 URI 将是 关注。

      /ResourceFile.xaml

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 2012-02-05
        • 1970-01-01
        • 2012-07-15
        • 2011-11-22
        相关资源
        最近更新 更多