WPF: proportional resize of two buttons

2019-09-13 19:43发布

I have a WPF form with two buttons in it. When the window is resized, each of the buttons should occupy half of the window's space at all times.
I can not get it to work.
How is it done?

<Window x:Class="ExampleWin.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:ExampleWin"
    mc:Ignorable="d"
    Title="Window" Height="200" Width="200" ToolTip="Tooltip" Topmost="True" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="CanResizeWithGrip">
<Border BorderBrush="#FF000000" BorderThickness="1,1,1,1" CornerRadius="5,5,5,5" UseLayoutRounding="True">
    <Grid>
        <Label x:Name="Backdrop" Content="Label" Margin="0,0,0,0" Foreground="{x:Null}" Background="#FFAD3838"/>
        <Button x:Name="Button1" Content="" Margin="1,1,99,1" BorderThickness="0" Background="#FF3B87BD"/>
        <Button x:Name="Button2" Content="" Margin="99,1,1,1" BorderThickness="0" Background="#FF59B483"/>
    </Grid>
</Border>

1条回答
混吃等死
2楼-- · 2019-09-13 20:21

add ColumnDefinitions to Grid and make them fill available space proportionally (Width="*" which is a default value)

put Button1 into 1st column (index=0) and Button2 into 2nd, using attached property Grid.Column. update Margin value if you don't need empty space near buttons

<Grid>
    <Grid.ColumnDefinitions>
         <ColumnDefinition/>
         <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Label x:Name="Backdrop" Grid.ColumnSpan="2" Content="Label" Margin="0,0,0,0" Foreground="{x:Null}" Background="#FFAD3838"/>
    <Button x:Name="Button1" Grid.Column="0" Content="" Margin="1" BorderThickness="0" Background="#FF3B87BD"/>
    <Button x:Name="Button2" Grid.Column="1" Content="" Margin="1" BorderThickness="0" Background="#FF59B483"/>
</Grid>
查看更多
登录 后发表回答