I have multibinding on Image control. I bind two properties one is type of bool(IsLogged) and one is typeof Uri (ProfilePhoto).
我在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>
I create converter, which convert BitmapImage to gray scale if property IsLogged is false.
我创建转换器,如果属性IsLogged为false,则将BitmapImage转换为灰度。
It look 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();
}
}
It works good if only I bind on image source property type fo BitmapImage, but I need bind property type of Uri.
如果我只在BitmapImage的图像源属性类型上绑定它,它工作得很好,但我需要绑定属性类型的Uri。
I have a fear of the creation variable BitmapImage in converter and as source use Uri. An return this variable as Source of image. I think this is not ideal way. Maybe I am wrong.
我担心转换器中的创建变量BitmapImage和源使用Uri。将此变量作为图像源返回。我认为这不是理想的方式。也许我错了。
What is your opinion
你有什么意见
Some elegant solution?
优雅的解决方案?
1 个解决方案
#1
11
Although you can do it with a converter, there is a much better option: using a shader effect. You'll find an implementation of a GreyscaleEffect on this page.
虽然您可以使用转换器,但有一个更好的选择:使用着色器效果。您将在此页面上找到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}" />
#1
11
Although you can do it with a converter, there is a much better option: using a shader effect. You'll find an implementation of a GreyscaleEffect on this page.
虽然您可以使用转换器,但有一个更好的选择:使用着色器效果。您将在此页面上找到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}" />