window坐标以及大小等属性做绑定后不能生效

分号 2025-02-10 17:23:41
    public class ObservableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    internal class MainWindowModel : ObservableObject
    {
        private double _locationX = 0;
        private double _locationY = 0;

        private double _width = 800;
        private double _height = 600;

        private string _title = "Test";

        public double LocationX
        {
            get { return _locationX; }
            set
            {
                _locationX = value;
                OnPropertyChanged();
            }
        }

        public double LocationY
        {
            get { return _locationY; }
            set { _locationY = value; OnPropertyChanged(); }
        }

        public double WindowWidth
        {
            get { return _width; }
            set { _width = value; OnPropertyChanged(); }
        }

        public double WindowHeight
        {
            get { return _height; }
            set
            {
                _height = value; OnPropertyChanged();
            }
        }

        public string MyTitle
        {
            get { return _title; }
            set { _title = value; OnPropertyChanged(); }
        }
    }

window的xaml代码:

<Window
    x:Class="WpfApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfApp2"
    xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="myWindow"
    Title="{Binding MyTitle}"
    Width="{Binding WindowWidth, UpdateSourceTrigger=Explicit}"
    Height="{Binding WindowHeight}"
    d:DataContext="{d:DesignInstance Type=local:MainWindowModel}"
    Background="{DynamicResource MaterialDesignPaper}"
    Left="{Binding LocationX}"
    Top="{Binding LocationY}"
    mc:Ignorable="d">
...
</Window>

为什么Binding后窗口的位置、大小都没有按照我设置的值来变化,但那个Title有效果。

我也尝试在窗口显示之后,点击上面的按钮,来主动设置viewmodel,但是也没效果。

有谁知道这是什么情况吗?

...全文
66 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
分号 02-11
  • 打赏
  • 举报
回复

找到问题所在了,和我发帖后思考的一样。就是TwoWay这个参数。

8,755

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧