WPF:Window SetBounds

And*_*rko 2 wpf

我在Windows.Forms中使用了SetBounds方法而不是Left,Top,Width,Height属性赋值,因为每次我赋值都会改变位置属性 - 窗口会改变它的位置.左,顶部,宽度,高度分配导致窗口移动4次,而SetBounds移动窗口一次(更好的UI体验,没有窗口犹豫).

当我迁移到WPF时,我发现没有SetBounds方法,看起来我必须逐步改变窗口大小和位置.

在一个窗口移动中更改WPF窗口位置的最佳方法是什么?

Tho*_*que 5

SetBounds在WPF中不可用,但您可以轻松地P /调用SetWindowPosAPI:

    private IntPtr _handle;
    private void SetBounds(int left, int top, int width, int height)
    {
        if (_handle == IntPtr.Zero)
            _handle = new WindowInteropHelper(this).Handle;

        SetWindowPos(_handle, IntPtr.Zero, left, top, width, height, 0);
    }

    [DllImport("user32")]
    static extern bool SetWindowPos(
        IntPtr hWnd,
        IntPtr hWndInsertAfter,
        int x,
        int y,
        int cx,
        int cy,
        uint uFlags);
Run Code Online (Sandbox Code Playgroud)

Left,Top,WidthHeight依赖属性会自动更新以反映新的边界.

  • 谢谢@Thomas!WPF的父亲抛弃了SetBounds方法,这太奇怪了.对我来说几乎令人难以置信的是,我们不得不将肮脏的黑客应用于这样一个很好的技术,开发用于从Windows小部件中抽象我们. (3认同)