更新时间:2023-12-03 10:42:40
您是否已验证您的方法确实成功并返回了正确的图像源?如果这样,重新分配Source
应该没有问题.如果您将新创建的图像本身加载到UI中,它会保留其源代码吗?
Have you verified that your method actually succeeds and returns the correct image source? If it does there should be no problem reassigning Source
. If you load the newly created image itself into the UI, does it retain its source?
this.Content = imgCreatedFromMethod; // where "this" is the window
顺便说一句,没有必要实现自己的转换功能.如果您有一个可以用作XAML的字符串,则可以直接调用XAML解析器用来构建图像源的转换器:
By the way, it would not be necessary to implement your own conversion function. If you have a string that would be valid as XAML, you can directly call the converter that the XAML parser uses to build an image source:
using System.Globalization;
using System.Windows.Media;
string stringValue = ...
ImageSourceConverter converter = new ImageSourceConverter();
ImageSource imageSource = converter.ConvertFrom(
null, CultureInfo.CurrentUICulture, stringValue);
System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo))
也可以动态检索转换器实例(在这种情况下为ImageSourceConverter
).
The converter instance (an ImageSourceConverter
in this case) can also be retrieved dynamically by System.ComponentModel.TypeDescriptor.GetConverter(typeof(TypeToConvertTo))
.
如果您使用数据绑定(如 TylerD87的答案),此转换也将自动完成.您还可以查看触发器并以这种样式定义两个图像:
This conversion will also be done automatically if you use data-binding as in TylerD87's answer. You can also look into triggers and define both images in the style like this:
<Image>
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="original path" />
<Style.Triggers>
<Trigger ...>
<Setter Property="Source" Value="new path" />
</Trigger>
</Style.Triggers>
</Style>
</Image.Style>
</Image>