public class AnimalConverter : IValueConverter
{
public static readonly AnimalConverter Instance = new();
public object? Convert( object? value, Type targetType, object? parameter, CultureInfo culture )
{
if (value is Animal animal)
{
if (targetType.IsAssignableTo(typeof(IImage)))
{
img = @"icons/generic-animal-placeholder.png"
switch (animal)
{
case Dog d:
img = d.IsGoodBoy ? @"icons/dog-happy.png" : @"icons/dog.png";
break;
case Cat:
img = @"icons/cat.png";
break;
// 等等
}
// 请看 https://docs.avaloniaui.net/docs/controls/image
return BitmapAssetValueConverter.Instance
.Convert(img, typeof(Bitmap), parameter, culture);
}
else if (targetType.IsAssignableTo(typeof(string)))
{
return !string.IsNullOrEmpty(animal.NickName) ?
$"{animal.Name} \"{animal.NickName}\"" : animal.Name;
}
}
// 用于错误类型的转换器
return new BindingNotification(new InvalidCastException(), BindingErrorType.Error);
}
public object ConvertBack( object? value, Type targetType, object? parameter, CultureInfo culture )
{
throw new NotSupportedException();
}
}