You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现窗口位置跟踪?现有尺寸跟踪代码无法更新位置

解决WPF窗口位置跟踪不更新问题

你的代码只监听了Window.Bounds的属性变化,但WPF中Bounds并非依赖属性,窗口移动时不会触发属性变更通知——只有窗口尺寸改变时,Bounds才会触发更新,这就是移动窗口时位置数据无法同步的原因。

修复方案是同时监听窗口的LocationChanged和SizeChanged事件,每次事件触发时主动获取最新的窗口Bounds并同步到ViewModel:

public MainWindow()
{
    InitializeComponent();
    var vm = new MainWindowViewModel();
    DataContext = vm;

    // 合并位置变化、尺寸变化的事件流
    var windowEvents = Observable.Merge(
        this.Events().LocationChanged.Select(_ => Unit.Default),
        this.Events().SizeChanged.Select(_ => Unit.Default)
    );

    windowEvents
        .Select(_ => this.Bounds)
        .Subscribe(bounds =>
        {
            vm.WindowResized(bounds);
            vm.WindowInfo = $"Position: {bounds.Position.X}, {bounds.Position.Y} | Size: {bounds.Width} x {bounds.Height}";
        });
}

ViewModel部分建议给属性补充getter(避免后续绑定或取值时出现问题),其余逻辑可保持不变:

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

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

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

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

    public double Y
    {
        get => _y;
        set => this.RaiseAndSetIfChanged(ref _y, value);
    }

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

    public void WindowResized(Rect bounds)
    {
        Width = bounds.Width;
        Height = bounds.Height;
        X = bounds.Position.X;
        Y = bounds.Position.Y;
    }
}

调整后,无论窗口移动还是调整尺寸,都会触发事件并同步最新的位置和尺寸数据。

内容的提问来源于stack exchange,提问作者wasdalt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 02:07:11