首页 > 解决方案 > 窗口的WPF MaxWidth绑定不起作用

问题描述

我试图绑定我的 Maxwidth Window而不是在 xaml 代码中设置它。

之前是:

<Window x:Class="WpfDialogs.GenericWindow"
    x:Name="BaseDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    WindowStartupLocation="CenterScreen"
    d:DataContext="{d:DesignInstance Type=wpfDialogs:DialogViewModel, IsDesignTimeCreatable=True}"
    Title="{Binding Title}"
    SizeToContent="WidthAndHeight"
    MaxWidth="1280" MaxHeight="600"
    MinWidth="400" MinHeight="400"
    WindowStyle="ToolWindow"
    ResizeMode="CanResizeWithGrip">

我将 xaml 更改为

MaxWidth="{Binding MaximumWidth, Mode=TwoWay}" MaxHeight="{Binding MaximumHeight, Mode=TwoWay}"

并添加到虚拟机:

    public double MaximumHeight
{
  get => mMaxHeight;
  set { mMaxHeight = value; }
}
public double MaximumWidth
{
  get => mMaxWidth;
  set { mMaxWidth = value; }
}

虚拟机已创建,DataContext并将Window设置为虚拟机。

setter 和 getter 都被调用(在 VM 的构造函数中设置并在创建视图时获取)但是在测试这个时,我可以尽可能多地最大化窗口。

我错过了什么?谢谢

标签: c#wpf

解决方案


您的属性未实现INotifyPropertyChanged,因此更改不会反映在 UI 中。

public class YourViewModel : INotifyPropertyChanged
{
   // ...other view model code.

   private double mMaxHeight;
   private double mMaxWidth;

   public double MaximumHeight
   {
      get => mMaxHeight;
      set
      {
         mMaxHeight = value;
         OnPropertyChanged();
      }
   }
   public double MaximumWidth
   {
      get => mMaxWidth;
      set
      {
         mMaxWidth = value;
         OnPropertyChanged();
      }
   }

   public event PropertyChangedEventHandler PropertyChanged;

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

推荐阅读