How to bind a Listview MaxHeight to the current windows height?
I'd like to limit the height to let's say 3/4 of the windows height.
How can I do that?
How to bind a Listview MaxHeight to the current windows height?
I'd like to limit the height to let's say 3/4 of the windows height.
How can I do that?
You could use a converter to calculate the height based on the Window height, something like this...
You need to pass the Window.ActualHeight into the converter - it will then return the window height multiplied by 0.75. If, for whatever reason, when the converter is hit, the Window.ActualHeight is null (or you've accidentally passed in something that can't be cast to a double) it will return double.NaN, which will set the height to Auto.
public class ControlHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
double height = value as double;
if(value != null)
{
return value * 0.75;
}
else
{
return double.NaN;
}
}
}
Bind this to your control like so... (obviously this is a very cut-down version of the xaml!)
<Window x:Name="MyWindow"
xmlns:converters="clr-namespace:NamespaceWhereConvertersAreHeld">
<Window.Resources>
<ResourceDictionary>
<converters:ControlHeightConverter x:Key="ControlHeightConverter"/>
</ResourceDictionary>
</Window.Resources>
<ListView MaxHeight="{Binding
ElementName=MyWindow, Path=ActualHeight,
Converter={StaticResource ControlHeightConverter}}"/>
</Window>
Another approach (without converter) would be to simply place it in a star-sized Grid. Certainly, this puts some restrictions on your layout. So, it depends on the other content whether this approach can be used or not.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.75*"/>
<RowDefinition Height="0.25*"/>
</Grid.RowDefinitions>
<ListView Grid.Row="0" VerticalAlignment="Top"/>
<!-- some other content -->
</Grid>
Since you wanted to specifiy the MaxHeight of the ListView, I have set the VerticalAlignment
to Top
, so that it does not use all the available space if it is not needed. Of course, you could also set this to Bottom
or Stretch
, depending on your requirements.