猿问

C# Wpf 绑定类型适配器

截至目前,我使用直接绑定到图像的源分配 TreeView 项的图像:

<DataTemplate DataType="{x:Type local:GeoPoint}">
     <StackPanel Orientation="Horizontal">
          <Image Source="{Binding Color}" Height="32" />
          <TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
     </StackPanel></DataTemplate>

颜色绑定是指包含PNG路径的字符串,例如“/Resources/red.png”

我想让自定义类型“MarkerColor”的颜色变量,一个包含几种颜色的枚举,并让图像源绑定引用这个值,这样如果

颜色 = MarkerColor.green;绑定将引用“/Resources/green.png”

注意PNG的名字不一定和MarkerColor的名字一样,需要一个“适配器”来转换类型

我知道如何在 Java Android SDK 中做到这一点,但不确定如何在 Wpf 中实现这一点


月关宝盒
浏览 125回答 1
1回答

犯罪嫌疑人X

您可以创建一个知道如何将枚举值转换为有效资源的转换器:public class ColorResourceConverter : IValueConverter{&nbsp; &nbsp; public object Convert(object value, Type targetType, object parameter, CultureInfo culture)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; MarkerColor color = (MarkerColor)value;&nbsp; &nbsp; &nbsp; &nbsp; Uri uri;&nbsp; &nbsp; &nbsp; &nbsp; switch(color)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case MarkerColor.Green:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uri = new Uri("Resources/green.png");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case MarkerColor.Red:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uri = new Uri("Resources/red.png");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uri = new Uri("Resources/default.png");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new BitmapImage(uri);&nbsp; &nbsp; }&nbsp; &nbsp; public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new NotSupportedException();&nbsp; &nbsp; }}用法:<DataTemplate DataType="{x:Type local:GeoPoint}">&nbsp; &nbsp; <DataTemplate.Resources>&nbsp; &nbsp; &nbsp; &nbsp; <local:ColorResourceConverter x:Key="ColorResourceConverter" />&nbsp; &nbsp; </DataTemplate.Resources>&nbsp; &nbsp; <StackPanel Orientation="Horizontal">&nbsp; &nbsp; &nbsp; &nbsp; <Image Source="{Binding Color, Converter={StaticResource ColorResourceConverter}}" Height="32" />&nbsp; &nbsp; &nbsp; &nbsp; <TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>&nbsp; &nbsp; </StackPanel></DataTemplate>
随时随地看视频慕课网APP
我要回答