BoolToVisibilityConverter这个转换器用于判断 bool 转 Collapsed(不占空间) 还是Hidden(占空间)。
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BoolToVisibilityConverter : IValueConverter
{
public BoolToVisibilityConverter()
: this(true)
{
}
public BoolToVisibilityConverter(bool collapsewhenInvisible)
: base()
{
CollapseWhenInvisible = collapsewhenInvisible;
}
public bool CollapseWhenInvisible { get; set; }
public Visibility FalseVisible
{
get
{
if (CollapseWhenInvisible)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Hidden;
}
}
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Visibility.Visible;
return (bool)value ? Visibility.Visible : FalseVisible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return true;
return ((Visibility)value == Visibility.Visible);
}
}
使用:
<converter:BoolToVisibilityConverter CollapseWhenInvisible="False" x:Key="_BoolToVisibilityConverter"/>
CollapseWhenInvisible="False" 为占空间,
CollapseWhenInvisible="True" 为不占空间,
默认 CollapseWhenInvisible="True" 。