无效的URI:无法确定URI的格式-C#
本文关键字:URI -C# 格式 无效 无法确定 | 更新日期: 2023-09-27 18:28:06
我试图将c#中资源字典的源设置为项目中文件夹的位置,但出现了上述错误。
有人能告诉我问题出在哪里吗?
这是代码:
myResourceDictionary.Source = new Uri("../Resources/Styles/Shared.xaml");
如果您需要更多信息,请告诉我。
您必须使用UriKind.Relative
myResourceDictionary.Source = new Uri("../Resources/Styles/Shared.xaml", UriKind.Relative);
即使在传递了UriKind.Relative
参数之后,我也一直遇到同样的问题。奇怪的是,一些Uris到XAML页面使用@Magnus建议的方法工作,但大多数页面都会抛出:
The format of the URI could not be determined
例外。
最后,我阅读了有关WPF应用程序的Pack Uris,它100%地解决了我的问题。
我开始使用这样的网址:
// 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);
希望这能帮助那些与我面临的同样问题作斗争的人。
我试图将窗口的背景设置为ImageBrush。
将UriKind.Absolute更改为UriKind.Relative为我解决了问题。
private void SetBackgroundImage()
{
ImageBrush myBrush = new ImageBrush
{
ImageSource =
new BitmapImage(new Uri("background.jpg", UriKind.Relative))
};
this.Background = myBrush;
}