创建一个转换器BoolToGridLengthConverter并将其作为静态资源放入您的App.xaml:
/// <summary>
/// Converts a boolean value to a grid length which is specified with a converter
/// parameter if the value is true, otherwise the grid lengthe will be zero.
/// <para>
/// If no parameter is specified the returned <see cref="Windows.UI.Xaml.GridLength"/> will be zero.
/// If the parameter cannot be parsed to a grid length then the returned <see cref="Windows.UI.Xaml.GridLength"/> will be zero.
/// If the value is a <see cref="bool"/> false, then the returned <see cref="Windows.UI.Xaml.GridLength"/> will be zero.
/// </para>
/// </summary>
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等。