Search code examples
c#mvvmreactiveuiavaloniaui

How do I track the position of the window?


Help with the implementation. I wrote the tracking code for the size of my window. Then I decided to add tracking of the window position. I tried to implement it, but it didn't work out.

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
        
        this.WhenAnyValue(window => window.Bounds)
            .Subscribe(bounds =>
            {
                var vm = (MainWindowViewModel)this.DataContext;
                vm.WindowResized(bounds);
                vm.WindowInfo = $"Position: {bounds.Position.X}, {bounds.Position.Y} | Size: {bounds.Width} x {bounds.Height}";
            });
    }

public class MainWindowViewModel : ReactiveObject
{
    private double _width;
    private double _height;
    private double _x;
    private double _y;

    public double Width
    {
        set => this.RaiseAndSetIfChanged(ref _width, value);
    }

    public double Height
    {
        set => this.RaiseAndSetIfChanged(ref _height, value);
    }
    public double X
    {
        set => this.RaiseAndSetIfChanged(ref _x, value);
    }

    public double Y
    {
        set => this.RaiseAndSetIfChanged(ref _y, value);
    }
    public void WindowResized(Rect bounds)
    {
        Width = bounds.Width;
        Height = bounds.Height;
        X = bounds.Position.X;
        Y = bounds.Position.Y;
    }

    
    private string _windowInfo;

    public string WindowInfo
    {
        set => this.RaiseAndSetIfChanged(ref _windowInfo, value);
    }
    
}

I need the position to be updated when moving the window.


Solution

  • I am not to familiar with AvaloniaUI events to command options, but in general your window has Position property and PositionChanged event. You can subscribe to this event to get the updated window position