【问题标题】:WPF application is not updating its Window.Left property at runtimeWPF 应用程序未在运行时更新其 Window.Left 属性
【发布时间】:2019-11-25 15:18:27
【问题描述】:

我试图让我的 wpf 应用程序在加载时占用我的右侧监视器。我的方法是创建一个存储屏幕宽度值(作为双精度值)的属性,然后将其绑定到 Window.Left 属性。但无论我做什么,应用程序窗口都不会移动到我的右侧显示器。

这是我的 xaml

<Window x:Class="Foo.FooView"
        .. declarations
        Title="{Binding Title}" 
    Left="{Binding ScreenOffset, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
        Height="800"
    Width="1920"
        SnapsToDevicePixels="True">

在我的视图模型中:

    public double ScreenOffset
    {
        get
        {
            return _screenOffset;
        }
        set
        {
            if (_screenOffset != value)
            {
                _screenOffset = value;
                RaisePropertyChanged(nameof(ScreenOffset));
            }
        }
    }
    private double _screenOffset = 0.0;

    public FooViewModel()
    {
        ScreenOffset = Application.Current.MainWindow.Width + defaultOffset; 
        //Application.Current.MainWindow.Width = 1920
        //defaultOffset = 10.0
    }

我的数据绑定适用于我的应用程序中的其他控件。唯一似乎不起作用的绑定只是 Left 属性。谁能看到我做错了什么?提前谢谢了。

【问题讨论】:

  • 你试过Mode=TwoWay绑定吗?另外,window的状态是什么?
  • @PavelAnikhouski 窗口状态设置为最大化,我尝试了 mode=twoWay。但窗口保持不变

标签: c# wpf


【解决方案1】:

您可以尝试将以下代码放入您的视图模型中吗:

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public double ScreenOffset
    {
        get
        {
            return _screenOffset;
        }
        set
        {
            if (_screenOffset != value)
            {
                _screenOffset = value;
                NotifyPropertyChanged();
            }
        }
    }

【讨论】:

    【解决方案2】:

    首先,我要感谢@PavelAnikhouski 和@Miguel Carreira 为帮助我解决这个问题所付出的时间和精力。所以,我的问题与我没有正确设置绑定这一事实无关。我的问题是我的 WindowState 从一开始就默认为 Maximized。这个site 也帮助我理解了这一点。我通过绑定我的 WindowState 并将其默认为 Normal 解决了我的问题。然后我设置新的 Left 值并将其绑定到属性,最后我将 WindowState 更改为 Maximized

    //setting up the dashboard window position, first
    //the WindowState has to be set to Normal
    WindowState = WindowState.Normal;
    
    //second, we get the offset value based on the configuration settings
    ScreenOffset = Application.Current.MainWindow.Width + defaultOffset;
    
    //third, we set the desired WindowState to Maximized
    WindowState = WindowState.Maximized;
    

    现在我的窗口出现在它想要的位置。再次感谢。

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2018-02-07
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多