创建一个转换器BoolToGridLengthConverter并将其放置在App.xaml
中作为静态资源:
public sealed class BoolToGridLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is bool) || !(parameter is string))
{
return new GridLength(0);
}
if (!((bool)value))
{
return new GridLength(0);
}
var str = parameter as string;
if (str.Equals("Auto"))
{
return new GridLength(0, GridUnitType.Auto);
}
if (str.Equals("*"))
{
return new GridLength(1, GridUnitType.Star);
}
if (str.EndsWith("*"))
{
var length = Double.Parse(str.Substring(0, str.Length - 1));
return new GridLength(length, GridUnitType.Star);
}
var len = Double.Parse(str);
return new GridLength(len);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
然后你可以在你的 XAML 中像这样使用它:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="{Binding HasValue, Converter={StaticResource BoolToGridLengthConverter}, ConverterParameter='*'}"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<!-- Some content here -->
</Grid>
<Grid Grid.Column="1" Visibility="{Binding HasValue, Converter={StaticResource BooleanToVisibilityConverter}}">
<!-- Some content here -->
</Grid>
</Grid>
转换器只会在布尔值为 true 时使用 ConverterParameter,否则列宽将设置为零。转换器参数可以是 Auto,也可以是例如 0.5* 或任何固定宽度,例如 50.5 等。