Convertor on ImageSource - Convert an image to grayscale

I have multi-link image management. I bind two properties: one type is bool (IsLogged) and one is typeof Uri (ProfilePhoto).

XAML:

<Image.Source > <MultiBinding Converter="{StaticResource avatarConverter}"> <Binding Path="ProfilePhoto"></Binding> <Binding Path="StatusInfo.IsLogged"></Binding> </MultiBinding> </Image.Source> </Image> 

I am creating a converter that converts BitmapImage to grayscale if the IsLogged property is false.

It looks like this:

 public class AvatarConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var image = values[0] as BitmapImage; string s = values[1].ToString(); bool isLogged = System.Convert.ToBoolean(s); if (!isLogged) { try { if (image != null) { var grayBitmapSource = new FormatConvertedBitmap(); grayBitmapSource.BeginInit(); grayBitmapSource.Source = image; grayBitmapSource.DestinationFormat = PixelFormats.Gray32Float; grayBitmapSource.EndInit(); return grayBitmapSource; } return null; } catch (Exception ex) { throw ex; } } return image; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

This works well if I only bind to the type of the image source property for BitmapImage, but I need the Uri binding property type.

I am afraid of creating a BitmapImage variable in the converter and as a source of using Uri. We return this variable as the image source. I think this is not an ideal way. Maybe I'm wrong.

what is your opinion

Some kind of elegant solution?

+4
source share
1 answer

Although you can do this with a converter, there is a much better option: using the shader effect. You will find the GreyscaleEffect implementation on this page .

 <Style x:Key="grayedIfNotLogged" TargetType="Image"> <Style.Triggers> <DataTrigger Binding="{Binding StatusInfo.IsLogged}" Value="False"> <Setter Property="Effect"> <Setter.Value> <fx:GrayscaleEffect /> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> ... <Image Source="..." Style="{StaticResource grayedIfNotLogged}" /> 
+10
source

Source: https://habr.com/ru/post/1335763/


All Articles