I have a WPF window that has a MaxWidth set, so when I hit the Maximize button, it maximizes vertically but not horizontally. This is expected behavior. However, the window always docks to the left side of the screen (Windows 7, if that matters) and I want it to be centered horizontally when Maximized. I tried adding the following StateChanged
event handler, but it doesn't seem to do anything:
private void wdw_mainWindow_StateChanged(object sender, EventArgs e)
{
switch (WindowState)
{
case WindowState.Maximized:
var windowWidth = (double)GetValue(WidthProperty);
Left = (SystemParameters.PrimaryScreenWidth / 2) - (windowWidth / 2);
break;
}
}
I set a breakpoint on the switch
statement and this code definitely gets hit when I hit the Maximize button in my app. However开发者_如何学运维, even after Left
gets set, the window remains firmly stuck to the left side of the screen. What's going on?
Aero Snap on Windows 7 is probably interfering with your attempt to center the window. Try turning off Aero Snap and see if you still have the problem.
http://www.sevenforums.com/tutorials/3069-aero-snap-turn-off.html
Change your windowWidth call (which will return NaN) to:
var windowWidth = this.ActualWidth;
Note: this was tested on XP SP3 - I don't have a Win7 machine available to me here at the moment.
Sorry - has the same behavior as Win7 when WindowState is Maximized. Perhaps the best thing to do is to catch when WindowState is changed to Maximized, and instead of actually setting the WindowState, set the size and position of the window in Normal mode.
Register to location changed also, and when both events occurs exec the logic, It'll do the trick.
精彩评论