我在Windows资源中有图片:
<Window.Resources>
<BitmapImage x:Key="Image1" UriSource="../Resources/MyImages/Image1.png" />
<BitmapImage x:Key="Image2" UriSource="../Resources/MyImages/Image2.png" />
<BitmapImage x:Key="Image3" UriSource="../Resources/MyImages/Image3.png" />
</Window.Resources>
它们的名称与我在模型中的枚举对象中的名称相匹配。
private ImagesEnum _currentImage;
public ImagesEnum CurrentImage
{
get { return _currentImage; }
set
{
if (_currentImage!= value)
{
_currentImage= value;
NotifyPropertyChanged("CurrentImage");
}
}
}
枚举:
public enum ImagesEnum
{
Image1,
Image2,
Image3
}
我想用枚举对象中的名称绑定资源的名称。
这样的事情:
<Image Source="{StaticResource {Binding CurrentImage}}" />
有办法做到这一点吗?
答案 0 :(得分:1)
假设CurrentImage
的类型为ImagesEnum
并代表要显示的当前图片,您可以使用值转换器:
public class ImagesEnumToSourceConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(value is ImagesEnum)
{
switch((ImagesEnum)value)
{
case ImagesEnum.Image1:
return "../Resources/MyImages/Image1.png";
case ImagesEnum.Image2:
return "../Resources/MyImages/Image2.png";
case ImagesEnum.Image3:
return "../Resources/MyImages/Image3.png";
}
}
return DependencyProperty.UnsetValue;
}
}
您的绑定应该是:
<Window.Resources>
<conv:ImagesEnumToSourceConverter x:Key="ImagesEnumToSource" />
</Window.Resources>
.....
<Image Source="{Binding CurrentImage, Converter={StaticResource ImagesEnumToSource}}" />