I'm trying to adjust my window height to the lesser resolution screen. Due to design of the project, this window is called from the ViewModel (though its content is written in XAML). So, to achieve this adjustment, I make the following in my ViewModel:
//_window is sort of singleton within the ViewModel, which is a true singleton
private static Window _window;
In method, that calls _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;
Then, in _window_LocationChanged
I adjust size:
...
// currentScreenHeight is the height of the screen, the window is on
WindowHeight = currentScreenHeight;
...
On move to other display with different resolution, this window 'dangles' on resize, quickly changing from previous, bigger size to the new one (looks like it changes on every movement, e.g. every pixel). Once I release left mouse button, it turns back to the previous size.
Why does it happen, and how can I painlessly decrease the size of the window programmatically?
EDIT: I made some changes to my code, so the height is only changed once, when the window has been moved to another screen. The base of the method to get current monitor is taken from here. I've changed it so, that it invokes an event, once the display has changed:
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);
}
}
}
Disregarding implementation of ScreenChangedEventArgs
, which only contains some fields, this method works fine, the event fires, method passed by its delegate executes, but still, the window returns to its original size immediately after I move the mouse.