Here is a great little generic BoolTo… converter. In the example below I use it to define the visibility of a textblock.
using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
namespace SilverlightGlimpse.Converters
{
public class BoolToVisibilityConverter : BoolToValueConverter<Visibility> { }
public class BoolToValueConverter<T> : MarkupExtension, IValueConverter
{
public T FalseValue { get; set; }
public T TrueValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return FalseValue;
return (bool)value ? TrueValue : FalseValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null && value.Equals(TrueValue);
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
}
<TextBlock Visibility="{Binding Path=IsInDebugMode,
Converter={local:BoolToVisibilityConverter
FalseValue=Collapsed,
TrueValue=Visible}}" />
Original author: http://geekswithblogs.net/codingbloke/archive/2010/05/28/a-generic-boolean-value-converter.aspx
No comments:
Post a Comment