Problems with binding to Window Height and Width

后端 未结 9 762
长发绾君心
长发绾君心 2020-12-05 13:46

I have some problems when I try to bind the height and width of a window to properties in my view model. Here is a small sample app to illustrate the problem. This is the co

9条回答
  •  北海茫月
    2020-12-05 14:33

    OK,

    I had the same problem and could not bind correctly the window dimensions (min, max, normal) to my viewmodel through XAML.

    I don't know why but you can acheive all those bindings without any problem if you do them by code instead of by XAML.

    Here is my C# code that worked :

    this.SetBinding(Window.WidthProperty, new Binding("Width") { Source = MyViewModel, Mode=BindingMode.TwoWay });
    this.SetBinding(Window.HeightProperty, new Binding("Height") { Source = MyViewModel, Mode=BindingMode.TwoWay });
    this.SetBinding(Window.MaxWidthProperty, new Binding("MaxWidth") { Source = MyViewModel });
    this.SetBinding(Window.MaxHeightProperty, new Binding("MaxHeight") { Source = MyViewModel });
    this.SetBinding(Window.MinWidthProperty, new Binding("MinWidth") { Source = MyViewModel });
    this.SetBinding(Window.MinHeightProperty, new Binding("MinHeight") { Source = MyViewModel });
    

    It is strange that it only works in code and not in XAML. It is even more strange that it binds TwoWay by default for mMin and Max dimensions but not for Normal dimensions for which you have to specify « Mode=BindingMode.TwoWay ».

    There should be a bug that Microsoft has to correct about this...

提交回复
热议问题