如何在 xaml 中将字符串强制转换为 Uri

本文关键字:转换 Uri 字符串 xaml | 更新日期: 2023-09-27 18:35:14

<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d" 
             Width="1024" Height="1280">
    <Grid Background="Black">
        <Image MaxWidth="500" MaxHeight="500" Source="{DynamicResource H_ThankYou_Image}" HorizontalAlignment="Center" VerticalAlignment="Center"/>  
    </Grid>
  <UserControl.Resources>
    <BitmapImage x:Key="H_ThankYou_Image" UriSource="{DynamicResource H_ThankYou_ImagePath}"/>
    <sys:String x:Key="H_ThankYou_ImagePath">"../../../../Graphics/Icon_Email.png"</sys:String>
  </UserControl.Resources>
</UserControl>

它表示 System.String 类型的对象不能应用于需要 System.Uri 类型的属性。

当我尝试这样的事情时:

<sys:Uri x:Key="H_ThankYou_ImagePath">"../../../../Graphics/Icon_Email.png"</sys:Uri>

它说名称"URI"在系统命名空间中不存在??

编辑1:

我尝试使用解决方案@Clemens建议:它适用于第一次运行(Icon_Email.png),但是当我尝试像这样动态更改值时: userControl.Resources["H_ThankYou_ImagePath"] = "../../../../Graphics/Icon_Email2.png"出现以下错误:

Cannot convert '<null>' from type '<null>' to type
'System.Windows.Media.ImageSource' for 'en-US' culture with default 
conversions; consider using Converter property of Binding. 
NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null).

如何在 xaml 中将字符串强制转换为 Uri

这个丑陋的黑客对我有用:

<Image DataContext="{DynamicResource H_ThankYou_ImagePath}" Source="{Binding}"/>

构建自 AnjumSKhan 的答案:

定义您的命名空间:

xmlns:sys="clr-namespace:System;assembly=System"

定义您的 URI

<sys:Uri>pack://application:,,,/YourAssemblyNameHere;component/Path/To/Image.jpg</sys:Uri>

所以问题是你引用了错误的程序集。只需将您的命名空间从 mscorlib 更改为 System,您就是黄金。

示例:

假设企鹅.jpg文件存在于根文件夹中。

命名空间映射

    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:sys1="clr-namespace:System;assembly=System"

资源声明

    <sys1:UriBuilder x:Key="UKey">
        <sys1:UriBuilder.Host>
            <x:Static Member="sys:String.Empty" />
        </sys1:UriBuilder.Host>
        <sys1:UriBuilder.Scheme>
            <x:Static Member="sys:String.Empty" />
        </sys1:UriBuilder.Scheme>
        <sys1:UriBuilder.Path>
            pack://application:,,,/Penguins.jpg
        </sys1:UriBuilder.Path>
    </sys1:UriBuilder>

用法:

<Image Source="{Binding Uri, Source={StaticResource UKey}}"/>