Maximizing WPF Doesn't Update Width?
Asked Answered
P

3

7

The Width property of the screen doesn't seem to update to the fully maximized width when maximizing a window. If I resize it everything works fine, but not when maximizing.

The code I have is as follows:

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
    UpdateColumns();
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    UpdateColumns();
}

private void UpdateColumns()
{
    ColumnCount = Math.Round(Width/150);
    statusBarItemColumnCount.Content = ColumnCount;
    button1.Content = ColumnCount + " " + Width;
}

private void Window_StateChanged(object sender, EventArgs e)
{
    UpdateColumns();
}
Photodisintegration answered 13/3, 2009 at 3:1 Comment(0)
B
15

Take a look at ActualWidth, rather than Width.

Battement answered 13/3, 2009 at 3:14 Comment(1)
Good fix. Any idea why the normal width wouldn't work though?Manche
O
3

try using ActualWidth instead of Width, that should fix it

Overweening answered 13/3, 2009 at 3:15 Comment(0)
S
1

Put this at the top of any code that needs width and height:

var RealWidth = Math.Max(Width,ActualWidth);

var RealHeight = Math.Max(Width,ActualHeight);

Then use RealWidth and RealHeight variables because they will always be right.

During Construction and before Showing ActualWidth and ActualHeight will be zero so Width and Height will be used.

After Maximizing Width and Height are still the pre-Maximized values but ActualWidth and ActualHeight will be used because they are larger.

If you followed all that and you want an elegant solution make two properties.

   private double RealWidth
    {
        get { return Math.Max(Width, ActualWidth); }
    }
    private double RealHeight
    {
        get { return Math.Max(Height, ActualHeight); }
    }

Then you can use RealWidth and RealHeight in all situations. Make the properties Internal or Public if you will need them outside the class.

Happy Programming Everybody!!!!!

Stefa answered 25/8, 2023 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.