Alex Rosenfeld Alex Rosenfeld -4 years ago 83
C# Question

MaxHeight MaxWidth binding does not change UI

I'm struggling with an issue where the following binding seems to have no impact on the UI:

<Toolbar MaxWidth="{Binding AllowedHorizontalSpace}" />

Property and field:

private int allowedHorizontalSpace;
public int AllowedHorizontalSpace {
get { return this.allowedHorizontalSpace; }
set {
this.allowedHorizontalSpace = value;

In the function that listens for monitor size changes:

this.AllowedHorizontalSpace = (int) (monitorWidth * 0.4)

What am I missing? The size of the control just does not want to change! The same error persists for MaxHeight as well.

I have tried manually changing this value using the tool snoop. The change is reflected in the control when I do this.

Answer Source

In comments, it comes out that when the monitor size changes, the setter for AllowedHorizontalSpace is called but not the getter.

The INotifyPropertyChanged implementation looks right from here, and the whole thing works correctly when AllowedHorizontalSpace is set via Snoop, so it is right, and the DataContext must be an instance of your viewmodel.

This kind of thing is commonly caused by there being a redundant viewmodel instance. Often, one is created in the XAML, and another is created in the codebehind constructor. The second instance assigned to DataContext is the one the property will be bound to, but you may be setting the property on the first. In that case the setter would execute on the first, but since no bindings are using that instance as a source, nothing would call the getter.

And you mention that the viewmodel's Initialize() method is unexpectedly being called twice, which is what I'd expect if the above were the case.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download