With a grid that has 2 columns, how will I be able to split it 50/50 in width only when the content of the second column is visible?
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</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>
If HasValue
is true, the grid needs to be split 50/50, else, the first column must occupy the whole screen.
Create a converter BoolToGridLengthConverter and put it in your App.xaml
as a static resource:
/// <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();
}
}
Then you can use it in your xaml like this:
<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>
The converter will use the ConverterParameter
only if the boolean value is true
, otherwise the column width will be set to zero. The converter parameter, can by Auto
, or for example 0.5*
or any fixed width for example 50.5
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With