0

我在 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}}" />

有没有办法做到这一点?

4

1 回答 1

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}}" />
于 2013-11-05T08:14:36.093 回答