WPF MVVM将图像控件绑定到资源中的图像 [英] WPF MVVM Binding Image Control to Image in Resources
问题描述
我的资源中有一个图像,我想根据使用转换器的输入文本字符串来显示该图像,实现该图像的方法是什么,因为它不会显示在我的应用程序中.
I have an Image in my resources I want to display based on an input text string where I am using a converter, what is the way to implement this as it is not displaying in my application.
在我的转换器EstateCodetoEstateImageConverter中
in my converter EstateCodetoEstateImageConverter I have
return Resources.Customer1EstateHeaderImage;
在我的XAML中,
<Image Source="{Binding EstateSheet.EstateCode, Converter={StaticResource EstateCodetoEstateImageConverter1}}" Stretch="Fill" Width="189" Height="112" />
我的理解是,绑定到源需要文件路径名而不是实际资源,我应该怎么做.
My understanding is that binding to the source needs the file Path name and not the actual resource, how should I do this.
推荐答案
在典型的WPF应用程序中,您不会将图像放入Resources.resx
并由Resources
类访问它们.相反,您只需将图像文件添加到Visual Studio项目中(也许在名为Images的文件夹中)并将其Build Action
设置为Resource
.现在,您可以通过 Pack URI 来访问它们,并且转换器的Convert方法可能如下所示:
In a typical WPF application you would not put images into Resources.resx
and access them by the Resources
class. Instead you would just add the image files to your Visual Studio project (perhaps in a folder called Images) and set their Build Action
to Resource
. Now you are able to access them by means of a Pack URI, and the Convert method of your converter might look like this:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object result = null;
switch ((EstateCode)value)
{
case EstateCode.EstateCode1:
result = new BitmapImage(new Uri("pack://application:,,,/Images/Estate1.jpg"));
break;
case EstateCode.EstateCode2:
result = new BitmapImage(new Uri("pack://application:,,,/Images/Estate2.jpg"));
break;
}
return result;
}
这篇关于WPF MVVM将图像控件绑定到资源中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!