Recently I read about an IValueConverter
which also inherits from MarkupExtension
. It was something like:
internal class BoolToVisibilityConverter : MarkupExtension, IValueConverter
{
private static BoolToVisibilityConverter converter;
public BoolToVisibilityConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
if ((bool)value)
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Visibility)
{
Visibility visibility = (Visibility)value;
if (visibility == Visibility.Collapsed)
{
return false;
}
}
return true;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return converter ?? (converter = new BoolToVisibilityConverter());
}
}
The usage than looks like:
<Button Content="Delete" Visibility="{Binding CanDelete, UpdateSourceTrigger=PropertyChanged, Converter={local:BoolToVisibilityConverter}"/>
I was used to use converters from a Resource like:
<loc:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
...
<Button Content="Delete" Visibility="{Binding CanDelete, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BoolToVisibilityConverter}"/>
My first question now is: What is the better way? What advantages does it have if I'm using the MarkupExtension-Version
(Beside the usage is easier to type)?
I also saw a very similar implementation which looks like:
internal class BoolToVisibilityConverter : MarkupExtension, IValueConverter
{
public BoolToVisibilityConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
if ((bool)value)
{
return Visibility.Visible;
}
}
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is Visibility)
{
Visibility visibility = (Visibility)value;
if (visibility == Visibility.Collapsed)
{
return false;
}
}
return true;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
If I understand it right, the first solution only creates one instance of this converter. The second one creates for every XAML a new instance of this converter, right?