wpfwindowwpf-positioning

Dynamically changing the start up location of a WPF window


This is a follow up question to an answered question [here][1].

There the startup position of a WPF window was defined in XAML. Now I'm wondering how to change those properties in code? For example could I say something like:

Window1.Top = 40 in the window load event handler? Or which window event would I need to set those for it dynamically alter the starting position?

The goal is to set the windows start position dynamically before it is rendered.


Solution

  • This is fairly easy to do in code:

    public partial class Window1 {
    
        public Window1()
        {
             InitializeComponent();
             this.Height = 500;
             this.Width = 500;
             this.WindowStartupLocation = WindowStartupLocation.Manual;
             this.Left = 0;
             this.Top = 0;
        }
    }
    

    You can set any of the parameters you wish, but if you're going to set Top/Left, make sure to set WindowStatupLocation (or have it set to manual in XAML).