首页 > 解决方案 > WPF 窗口大小绑定

问题描述

我正在尝试将窗口高度调整为分辨率较低的屏幕。由于项目的设计,这个窗口是从 ViewModel 调用的(尽管它的内容是用 XAML 编写的)。因此,为了实现这种调整,我在 ViewModel 中进行了以下操作:

//_window is sort of singleton within the ViewModel, which is a true singleton
private static Window _window;

在方法中,调用_window.Show()

//_instance is an instance of the ViewModel. Font size is also adjusted.
Binding fontSizeBinding = new Binding(nameof(FontSize));
fontSizeBinding.Source = _instance;

Binding windowHeightBinding = new Binding(nameof(WindowHeight)) 
{
    Source = _instance,
    Mode = BindingMode.TwoWay
};

_window.SetBinding(Window.FontSizeProperty, fontSizeBinding);
_window.SetBinding(Window.HeightProperty, windowHeightBinding);

_window.LocationChanged += _instance._window_LocationChanged;

然后,在_window_LocationChanged我调整大小:

...
// currentScreenHeight is the height of the screen, the window is on
WindowHeight = currentScreenHeight;
...

在移动到具有不同分辨率的其他显示器时,此窗口在调整大小时“悬空”,从以前的更大尺寸快速更改为新的(看起来它在每次移动时都会发生变化,例如每个像素)。一旦我松开鼠标左键,它就会变回原来的大小。

为什么会发生这种情况,如何以编程方式轻松减小窗口的大小?

编辑: 我对我的代码进行了一些更改,因此当窗口移动到另一个屏幕时,高度只更改一次。获取当前监视器的方法的基础取自这里。我已经对其进行了更改,一旦显示更改,它就会调用一个事件:

private Screen _currentScreen;
public Screen CurrentScreen
{
    get => _currentScreen;
    private set
    {
        if (_currentScreen == null || _currentScreen.DeviceName != value.DeviceName)
        {
            _currentScreen = value;
            ScreenChangedEventArgs args = new ScreenChangedEventArgs(value,
                GetRect(value.Bounds), GetRect(value.WorkingArea), value.Primary, 
                value.DeviceName );
            CurrentScreenChanged?.Invoke(_currentWindow, args);
        }
    }
}

忽略ScreenChangedEventArgs仅包含一些字段的 的实现,此方法工作正常,事件触发,其委托传递的方法执行,但仍然,在我移动鼠标后窗口立即恢复到其原始大小。

标签: c#wpf

解决方案


推荐阅读