Konwertery – krótkie klasy i jednocześnie bardzo przydatne elementy, bez których bindowanie niektórych wartości w XAMLu byłoby bardzo kłopotliwe. Mają one zastosowanie w projektach typu Winodws Phone, Silverlight oraz WPF. Praktycznie w większości tego typu projektów mnożna od razu przekleić te najważniejsze. Dla mnie są to:
[list]
- string / Uri -> BitmapImage
- bool -> Visibility
- Color -> SolidColorBrush
- String + StringFormat
[/list]
W dalszej części wiadomości znajdziecie ich implementację…
BitmapImageConverter
public class BitmapImageConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
string stringValue = value as string;
if (stringValue != null)
{
return new BitmapImage(new Uri(stringValue, UriKind.RelativeOrAbsolute));
}
Uri uriValue = value as Uri;
if (uriValue != null)
{
return new BitmapImage(uriValue);
}
throw new NotSupportedException();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
BooleanToVisibilityConverter
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value != null && (bool)value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((Visibility)value) == Visibility.Visible;
}
}
ColorToBrushConverter
public class ColorToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value == null)
{
return new SolidColorBrush(Colors.Transparent);
}
if (value is Color)
{
return new SolidColorBrush((Color)value);
}
string stringValue = value as string;
if (stringValue != null)
{
stringValue = stringValue.Replace("#", string.Empty);
return new SolidColorBrush(Color.FromArgb(
Byte.Parse(stringValue.Substring(0,2), NumberStyles.HexNumber),
Byte.Parse(stringValue.Substring(2,2), NumberStyles.HexNumber),
Byte.Parse(stringValue.Substring(4,2), NumberStyles.HexNumber),
Byte.Parse(stringValue.Substring(6,2), NumberStyles.HexNumber)));
}
throw new NotSupportedException();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
StringFormatConverter
public class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (parameter == null && value == null)
{
return String.Empty;
}
return parameter == null ? value.ToString()
: String.Format(CultureInfo.CurrentCulture, parameter.ToString(), value);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}


Zostaw komentarz