我想根据枚举值显示不同的图标/图像。例如,如果我有以下枚举:
public enum UploadStatus
{
Unknown = 0,
WaitingToUpload = 10,
Uploading = 20,
Uploaded = 30,
UploadFailed = 40
}
我想编写看起来像这样的XAML:
...
<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范例。
有任何指示或建议吗?
答案 0 :(得分:15)
这是一个值转换器,它维护“XAML范例”,即在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中的用法: -
<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>
当枚举类型的绑定属性时,可以使用此转换器: -
<Image Source="{Binding Status, Converter={StaticResource Icons}}" />
答案 1 :(得分:0)
您的EnumImage
可以使用Image
与DataTrigger
:
<Image Tag="{Binding Gender}" Width="48" Height="48">
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" Value="Male">
<Setter Property="Source" Value="/Resources/Client_Male.png"/>
</DataTrigger >
<DataTrigger Binding="{Binding Path=Tag, RelativeSource={RelativeSource Self}}" Value="Female">
<Setter Property="Source" Value="/Resources/Client_Female.png"/>
</DataTrigger >
</Style.Triggers>
</Style>
</Image.Style>
</Image>