Right now I have a datagrid within a window that fills up after a button is clicked somewhere, whenever the datagrid is filled up, it pushes past the window's current size and expands the window further. What is the way to make sure the datagrid can only expand up to the window's current size at the moment.
I require the window to be able to be manually resized afterwards, so setting max height is not possible.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="40" MinHeight="40"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto" MinWidth="250"/>
</Grid.ColumnDefinitions>
<GroupBox Grid.Column="0 Margin="10,0,5,0">
<Grid MaxHeight="{Binding ActualHeight, ElementName= AddressTable}">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<DataGrid Name="AddrTable" VerticalScrollBarVisibility="Auto"
Grid.Row="0"
I'm not sure if this is what you want, but one way to make the MaxHeight dynamic with the Height
of the Window is by using RelativeSource
. Let me explain:
In your Grid
, you set the MaxHeight
to be the ActualHeight
of the Window. To do so, you just need to bind
MaxHeigth = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ActualHeight}"
Now, this is not a great solution due to the fact that there are margins, paddings and more items inside the window. So what you want is to make the Grid
proportional to the ActualHeight
. Therefore, you need a Converter.
I've made you this one, that returns a percentage of the value.
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return 0:
if (parameter == null)
return (double)value;
var split = parameter.ToString().Split('.');
var parameterDouble = double.Parse(split[0]) + double.Parse(split[1]) / Math.Pow(10, split[1].Length);
return (double)value * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
Once you have defined it in a ResourceDictionary
<converters:SizePercentageConverter x:Key="PercentageConverter" />
You can call it in your MaxHeight
. For instance, if you wanted it to be 70% of the ActualHeight
, you just need to write
MaxHeight = "{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=ActualHeight, Converter={StaticResource PercentageConverter}, ConverterParameter=0.7}"
Otherwise, if you could also create a Converter that substracted a value. For exemple, once binded it returns ActualHeight
- parameter
.
I hope this may help, and let me know how it goes.