2011-01-16 4 views
4

Image 컨트롤에 멀티 바인딩이 있습니다. 나는 하나의 bool (IsLogged) 유형과 Uri (ProfilePhoto)의 두 가지 속성을 바인딩합니다.ImageSource의 변환기 - 이미지를 회색조로 변환

XAML : 부동산 IsLogged이 false 인 경우 규모를 회색으로 BitmapImage를 변환

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

내가 컨버터를 작성.

그것은 다음과 같이 :

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(); 
    } 
} 

단지 내가 BitmapImage FO 이미지 소스 속성 유형에 결합하는 경우가 좋은 작동하지만, 나는 열린 우리당의 바인딩 속성 유형이 필요합니다.

변환기에서 BitmapImage라는 생성 변수에 대한 두려움이 있으며 소스로 Uri를 사용합니다. 이 변수를 이미지 원본으로 반환하십시오. 나는 이것이 이상적인 방법이 아니라고 생각한다. 어쩌면 내가 틀렸어.

당신의 의견

일부 우아한 해결책은 무엇인가?

답변

10

변환기로도 할 수 있지만 셰이더 효과를 사용하는 것이 훨씬 더 좋습니다. 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}" /> 
+0

흥미로운 솔루션을 고맙게 생각합니다. –

+0

어떤 xml 네임 스페이스가 'fx'가 – LordWilmore

+0

@LordWilmore로 매핑 되었습니까? 전혀 모르겠지만 ... GreyscaleEffect 클래스를 사용했던 페이지는 더 이상 사용할 수 없습니다. –