Here is a Value converter which maintains the "XAML paradigm" that is the relationship between enum values and images is maintained in XAML.
[ContentProperty("Items")]
public class EnumToObjectConverter : IValueConverter
{
public ResourceDictionary Items { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string key = Enum.GetName(value.GetType(), value);
return Items[key];
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException("This converter only works for one way binding");
}
}
Note that this is very generic it actually maps values of any enum type to any arbitary object. This is what its usage looks like in Xaml:-
<Grid.Resources>
<local:EnumToObjectConverter x:Key="Icons">
<ResourceDictionary>
<BitmapImage x:Key="Unknown" UriSource="/images/unknown.png" />
<BitmapImage x:Key="WaitingToUpload" UriSource="/images/clock.png" />
<BitmapImage x:Key="Uploading" UriSource="/images/upload.png" />
<BitmapImage x:Key="Uploaded" UriSource="/images/tick.png" />
<BitmapImage x:Key="UploadFailed" UriSource="/images/error.png" />
</ResourceDictionary>
</local:EnumToObjectConverter>
</Grid.Resources>
This converter can be used when binding property of the enum type:-
<Image Source="{Binding Status, Converter={StaticResource Icons}}" />
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…