最近我读到了一个IValueConverter
也继承自MarkupExtension
. 它是这样的:
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());
}
}
用法比看起来像:
<Button Content="Delete" Visibility="{Binding CanDelete, UpdateSourceTrigger=PropertyChanged, Converter={local:BoolToVisibilityConverter}"/>
我习惯于使用来自 Resource 的转换器,例如:
<loc:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter"/>
...
<Button Content="Delete" Visibility="{Binding CanDelete, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource BoolToVisibilityConverter}"/>
我现在的第一个问题是:更好的方法是什么?如果我使用的是MarkupExtension-Version
(除了用法更容易输入),它有什么优势?
我还看到了一个非常相似的实现,如下所示:
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;
}
}
如果我理解正确,第一个解决方案只会创建这个转换器的一个实例。第二个为每个 XAML 创建了这个转换器的一个新实例,对吗?