I made a quick viewmodel with a RelayCommand (I use mvvmlight) tied to a button click that expands / contracts a window and centers it.
public class MoreJunk : ViewModelBase
{
private bool HeightSet = false;
private double oldHeight;
private double oldWidth;
public RelayCommand ResizeAndCenterWindowCommand { get; private set; }
private void ResizeAndCenterWindow()
{
if (!HeightSet)
{
Application.Current.MainWindow.Height = 300;
Application.Current.MainWindow.Width = 500;
Application.Current.MainWindow.Top = ((SystemParameters.PrimaryScreenHeight - 300) / 2);
Application.Current.MainWindow.Left = ((SystemParameters.PrimaryScreenWidth - 500) / 2);
HeightSet = true;
}
else
{
Application.Current.MainWindow.Height = oldHeight;
Application.Current.MainWindow.Width = oldWidth;
Application.Current.MainWindow.Top = ((SystemParameters.PrimaryScreenHeight - oldHeight) / 2);
Application.Current.MainWindow.Left = ((SystemParameters.PrimaryScreenWidth - oldWidth) / 2);
HeightSet = false;
}
}
#region " Constructor "
/// <summary>
/// MoreJunk
/// </summary>
public MoreJunk()
{
this.ResizeAndCenterWindowCommand = new RelayCommand(ResizeAndCenterWindow);
this.oldHeight = Application.Current.MainWindow.Height;
this.oldWidth = Application.Current.MainWindow.Width;
}
#endregion
}
I can drag and move the window, click the button, and the window centers and resizes itself without a problem.
My simple grid on the page:
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="10"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Button Grid.Row="2" Content="SizeMe" Command="{Binding ResizeAndCenterWindowCommand}"></Button>
</Grid>