yan yankelevich
yan yankelevich

Reputation: 945

WPF MVVM - Disabled checkbox requires a setter on property binded to IsEnabled to work

A coworker of mine just encountered some weird behaviour with binding in Wpf.

First of all here is what he wanted to achieve :

In code the property looks like this :

C#

public bool IsFooBarFilterEnabled
{
    get
    {
        return _isFoo && _isBar;
    }
}

XAML

<CheckBox IsChecked="{Binding IsFooBarFilterEnabled}" IsEnabled="False" />

Then whener he sets _isFoo or _isBar he calls RaisePropertyChanged(()=>IsFooBarFilterEnabled);

So far everything looks fine to me... but his code doesn't work.

We had to add an empty setter like this :

public bool IsFooBarFilterEnabled
{
    get
    {
        return _isFoo && _isBar;
    }
    set{}// that's not what i would call beautifull code
}

That's where my question is. If the checkbox is disabled, the setter on IsFooBarFilterEnabled should never be called. So why do have to create one to avoid crashes ? What is our mistake on this ?

Upvotes: 1

Views: 832

Answers (1)

appa yip yip
appa yip yip

Reputation: 1454

By default, the Binding Mode is set to TwoWay, which means that both the property and the component must be updated if the other is changed. Also, the ComboBox is disabled now, it doesn't mean it'll be disabled always.

You must either create the empty set (if you wish to continue with the TwoWay binding) or set the Binding Mode as OneWay (which means that the component should be updated when the property changes, but not the other way around)

Here's an example:

<CheckBox IsChecked="{Binding IsFooBarFilterEnabled, Mode=OneWay}" IsEnabled="False" />

Upvotes: 2

Related Questions