【问题标题】:How could convert the resource to the other type in the xaml file?如何将资源转换为 xaml 文件中的其他类型?
【发布时间】:2023-03-23 12:15:01
【问题描述】:

我的英语水平很差,因为我不是以英语为母语的人。 希望你能理解。

我想将字符串资源转换为 ImageSource。

例如,字符串类型资源在Linkes.xaml中定义如下。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Wpf.UI.Basic.DarkTheme"
                    xmlns:system="clr-namespace:System;assembly=mscorlib">

    <system:String x:Key="CloseImagePath">/Wpf.UI.Basic;component/Resources/Close.png</system:String>

</ResourceDictionary>

我在Window.xaml(自定义控件)中使用了上述资源,如下所示。

<Image x:Name="CloseImage"
       Source="{DynamicResource CloseImagePath}"
       Stretch="None"
       Margin="4"/>

但是当我像上面那样尝试时,我遇到了字符串类型无法转换为 ImageSource 类型的错误。

所以我尝试添加一个从字符串转换为 ImageSource 的转换器,但由于无法将转换器添加到资源中,我不能这样做。

所以我想将转换器添加到DynamicResource中以从字符串类型转换为ImageSource类型。

我应该怎么做才能实现上述目标? 我想听听你的建议。

感谢您的阅读。

【问题讨论】:

  • 您可以将资源声明为 BitmapImage:,而不是字符串。 &lt;BitmapImage x:Key="CloseImage" UriSource="/Wpf.UI.Basic;component/Resources/Close.png"/&gt;
  • 哦,谢谢你我解决了这个问题

标签: wpf resources converters


【解决方案1】:

声明一个 BitmapImage 资源而不是一个字符串:

<BitmapImage x:Key="CloseImage" UriSource="/Wpf.UI.Basic;component/Resources/Close.png"/>

...

<Image Source="{DynamicResource CloseImage}" .../>

【讨论】:

  • 感谢您的回答。我按照您的建议解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2023-03-18
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 2015-09-23
  • 2016-09-26
相关资源
最近更新 更多