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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9738174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:38:25  来源:igfitidea点击:

Invalid URI: The format of the URI could not be determined - C#

c#

提问by user589195

Im trying to set the source of a resource dictionary in c# to a location of a folder within the project, but get the above error.

我试图将 c# 中的资源字典的源设置为项目中文件夹的位置,但出现上述错误。

Could someone advise what the issue is please?

有人可以建议问题是什么吗?

Heres the code:

代码如下:

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

Please let me know if you need anymore information.

如果您需要更多信息,请告诉我。

采纳答案by Magnus Johansson

You have to use UriKind.Relative

你必须使用 UriKind.Relative

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

回答by saurabhj

I kept running into the same issue even after passing the UriKind.Relativeargument. The weird bit was that some of the Uris to XAML pages were working using the method @Magnus suggested - but most of them would throw the:

即使在通过UriKind.Relative参数后,我仍然遇到同样的问题。奇怪的是,一些 Uris 到 XAML 页面正在使用@Magnus 建议的方法工作 - 但其中大多数会抛出:

The format of the URI could not be determined

The format of the URI could not be determined

exception.

例外。

Finally, I read up on Pack Urisfor WPF applications which solved my problem a 100%.

最后,我阅读了WPF 应用程序的Pack Uris,它 100% 解决了我的问题。

I started using urls like this:

我开始使用这样的网址:

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

or

或者

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

Hope this helps someone struggling with the same issues I was facing.

希望这可以帮助那些与我面临的同样问题苦苦挣扎的人。

回答by TidyDev

I was trying to set the background of a window to an ImageBrush.

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

Changing UriKind.Absolute to UriKind.Relative fixed the problem for me.

将 UriKind.Absolute 更改为 UriKind.Relative 为我解决了这个问题。

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