如何仅使用 XAML 显示不同的 Enum 图标? [英] How to display different Enum icons using XAML only?
问题描述
我想根据枚举值显示不同的图标/图像.例如,如果我有以下枚举:
I want to show a different icon/image depending on an enum value. For example, if I had the following enum:
public enum UploadStatus
{
Unknown = 0,
WaitingToUpload = 10,
Uploading = 20,
Uploaded = 30,
UploadFailed = 40
}
我想编写如下所示的 XAML:
I'd like to write XAML that looks something like this:
...
<EnumImage Value="{Binding Path=CurrentStatus}">
<EnumImageItem Value="Unknown" Image="/images/unknown.png" />
<EnumImageItem Value="WaitingToUpload" Image="/images/clock.png" />
<EnumImageItem Value="Uploading" Image="/images/upload.png" />
<EnumImageItem Value="Uploaded" Image="/images/tick.png" />
<EnumImageItem Value="UploadFailed" Image="/images/error.png" />
</EnumImage>
...
我发现很多帖子都建议自定义 IValueConverters,但这些解决方案不符合 XAML 范式.
I've found many posts suggesting custom IValueConverters, but those solutions don't fit the XAML paradigm.
有任何指示或建议吗?
推荐答案
这里是一个值转换器,它维护XAML 范式",即枚举值和图像之间的关系在 XAML 中维护.
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");
}
}
请注意,这是非常通用的,它实际上将任何枚举类型的值映射到任何任意对象.这是它在 Xaml 中的用法:-
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}}" />
这篇关于如何仅使用 XAML 显示不同的 Enum 图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!