我在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}}" />
有办法做到这一点吗?
假设
CurrentImage
是ImagesEnum
类型并代表当前要显示的图像,您可以使用值转换器:
public class ImagesEnumToSourceConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if(value is ImagesEnum imagesEnum)
{
switch(imagesEnum)
{
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}}" />