Home > OS >  How to make the button one third of the size of the window? WPF C#
How to make the button one third of the size of the window? WPF C#

Time:09-16

I want to specify the width of my button in percent. Is there something like width: 33% in WPF? this is my button:

<Button x:Name="btnWebsite" Content="Button" HorizontalAlignment="Left" Margin="58,342,0,0" VerticalAlignment="Top" Height="43" Width="139"/>

thanks for the help :D

CodePudding user response:

You could put the Button in a star-sized Grid that fills the window:

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

        <Button Content="..." Grid.Column="1" />
    </Grid>
</Window>

Or handle the SizeChanged event of the window and set the button's Width property to this.Width / 3.0:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        SizeChanged  = OnSizeChanged;
    }

    private void OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        btnWebsite.Width = Width / 3.0;
    }
}
  • Related