Problems with binding to Window Height and Width

后端 未结 9 760
长发绾君心
长发绾君心 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:28

    I had the same problem and I noticed that it depends whether height or width is written first in xaml. If height is first, then Binding work only for it and vice versa. The solution was to set Binding mode to 'TwoWay': The project I have made was with MS Studio 2010 and .NET 4.0

    0 讨论(0)
  • 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...

    0 讨论(0)
  • 2020-12-05 14:34

    I will try to answer my own question. The bindings are working, but we can't really be sure that the layout system asks for e.g. the Width property of the window.

    From MSDN:

    If this element is a child element within some other element, then setting this property to a value is really only a suggested value. The layout system as well as the particular layout logic of the parent element will use the value as a nonbinding input during the layout process. In practical terms, a FrameworkElement is almost always the child element of something else; even when you set the Height on Window. (For Window, that value is used when the underlying application model establishes the basic rendering assumptions that create the Hwnd that hosts the application.)

    A solution that seems to work is to bind the WindowWidth property to MinWidth and MaxWidth, as well as Width. One of these will be retrieved, at least in the test scenario I was using above.

    0 讨论(0)
提交回复
热议问题