I am developping a WPF application in XAML. I am a beginner and I have an issue with my button. I need to set its height as a proportion of its container which is a grid. I saw that the height can be set to a value or to "Auto", but I don't know how to say to my button that his height must be 3/4 of the height of the grid in which it is contained.
Does anybody know how to deal with that ? Is it possible to do that with XAML ?
The objective is that when the grid grows, the button grows with it.
Any help would be appreciate.
Thanks
Here is the code I wrote :
<Window x:Class="WpfAppButtonSize.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfAppButtonSize"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid Height="100" Width="250" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Content="Button 1" FontSize="30" Height="75" Width="150"/>
</Grid>
</Grid>
For the button, instead of Height="75", I would like to say Height=0.75 * Grid Height
CodePudding user response:
The easiest way is to place the button within its own grid, with rows sized approporiately to generate the spacing.
e.g.
<Grid ...>
<Grid Grid.Row="???" Grid.Column="???" ...>
<Grid.RowDefinitions>
<RowDefinition Height="3*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" ... />
</Grid>
</Grid>
CodePudding user response:
If you give your Grid and your Button a name by specifying the x:Name
attribute, you could set the Button's Height
in the code behind whenever the Grid's size changes.
XAML
<Grid x:Name="MyGrid">
<Button x:Name="MyButton" />
</Grid>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
MyGrid.PropertyChanged = (s,e) =>
{
if(e.PropertyName == nameof(MyGrid.Height))
{
MyButton.Height = MyGrid.Height * 0.75;
}
}
}