无效的URI:无法确定URI的格式 - C#

6

我正在尝试将C#中资源字典的源设置为项目内文件夹的位置,但是遇到了上述错误。

请问有人能指导一下问题所在吗?

以下是代码:

myResourceDictionary.Source = new Uri("../Resources/Styles/Shared.xaml");

请告诉我是否需要更多信息。


由于这是一个文件路径,请使用 \ 而不是 /。 - jrummell
3个回答

11
您需要使用UriKind.Relative
myResourceDictionary.Source = new Uri("../Resources/Styles/Shared.xaml",  UriKind.Relative);

4
我在传递UriKind.Relative参数后仍然遇到了相同的问题。奇怪的是,一些指向XAML页面的URI使用@Magnus建议的方法可以正常工作 - 但大多数会抛出以下异常:The format of the URI could not be determined

最终,我阅读了有关WPF应用程序的打包URI的文章,解决了我的问题100%。
我开始使用此类URL:
// ResourceFile is in the Root of the Application
myResourceDictionary.Source = 
    new Uri("pack://application:,,,/ResourceFile.xaml", UriKind.RelativeOrAbsolute);

或者

// ResourceFile is in the Subfolder of the Application
myResourceDictionary.Source = 
    new Uri("pack://application:,,,/SubFolder/ResourceFile.xaml", UriKind.RelativeOrAbsolute);

希望这能帮助一些遇到我曾经面临的相同问题的人。

0

我试图将窗口的背景设置为ImageBrush。

将UriKind.Absolute更改为UriKind.Relative,问题得到解决。

private void SetBackgroundImage()
{
    ImageBrush myBrush = new ImageBrush
    {
        ImageSource =
        new BitmapImage(new Uri("background.jpg", UriKind.Relative))
    };
    this.Background = myBrush;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接