0

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

mm8
  • 163,881
  • 10
  • 57
  • 88
Noel
  • 61
  • 9
  • I think something (image, code) did not show up in your question. – eglease Sep 14 '21 at 15:36
  • You can get the width of the form and modify the width of your button using it. Use `.ActualHeight` and `.ActualWidth` to get the actual values. – eglease Sep 14 '21 at 15:37

1 Answers1

3

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;
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thank you so much, i really appreciate that! – Noel Sep 15 '21 at 07:40
  • When I maximize the window with the Maximize button, the button does not adjust. How can I change this? – Noel Sep 30 '21 at 10:03
  • It should adjust using my sample markup, i.e. if the `Grid` is the `Content` of the window being maximized. – mm8 Oct 01 '21 at 14:15