ImageSource上的转换器 - 将图像转换为灰度

4 wpf uri image converter

我在Image控件上有多个绑定.我绑定两个属性,一个是bool(IsLogged)类型,一个是typeof Uri(ProfilePhoto).

XAML:

                                <Image.Source >
                                    <MultiBinding Converter="{StaticResource avatarConverter}">
                                        <Binding Path="ProfilePhoto"></Binding>
                                        <Binding Path="StatusInfo.IsLogged"></Binding>
                                    </MultiBinding>
                                </Image.Source>
                            </Image>
Run Code Online (Sandbox Code Playgroud)

我创建转换器,如果属性IsLogged为false,则将BitmapImage转换为灰度.

它看起来像这样:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我只绑定BitmapImage的图像源属性类型,它的效果很好,但我需要绑定属性类型的Uri.

我担心转换器中的创建变量BitmapImage和源使用Uri.将此变量作为图像源返回.我认为这不是理想的方式.也许我错了.

你有什么意见

优雅的解决方案?

Tho*_*que 11

虽然您可以使用转换器,但有一个更好的选择:使用着色器效果.您将在此页面上找到GreyscaleEffect的实现.

<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}" />
Run Code Online (Sandbox Code Playgroud)