0
votes

I found a difference on property binding between UserControl and a normal Control.

For example, assuming that the markup contains the following usercontrol:

<myCtrl:DemoControl Level="{Binding Alarm.AlarmLevel}" />

"Level" is an int dependency property created in "Control". "Alarm" is an object of type Inotifypropertychanged, with a field AlarmLevel.

public bool AlarmLevel
{
    get 
    {
        return this._alarmLevel;
    }
    set
    {
        this._alarmLevel = value;
        NotifyPropertyChanged("AlarmLevel");
    }
}

Inside the usercontrol, I did the following:

LevelProperty = DependencyProperty.Register("Level", typeof(int), typeof(DemoControl), new UIPropertyMetadata(0, isLevelChanged));

The strange thing is that when assign AlarmLevel to a value, if the value changes, the usercontrol property got updated. While if value remains the same, no update. BUT IN BOTH CASES, "NotifyPropertyChanged" gets called !

For example, if AlarmLevel==1,

Alarm.AlarmLevel = 2; // the "isLevelChanged" got called
Alarm.AlarmLevel = 1; // the "isLevelChanged" not called

I remember that with the normal control, whenever PropertyChanged is called, the property gets updated. Anybody knows why? Many thanks!

1
Your observation is correct and done by design of the DependencyProperty. The DependencyProperty has some logic inside and only updates if the value changes. That avoids unnecessary updates of the GUI (which are quite costly). On the other hand there are rare cases where you need to work around that behavior. - gomi42
Thank you. The "logic inside" is exactly what I have been searching for. - captainst

1 Answers

0
votes

There is a bug in your AlarmLevel setter. It should be:

if (_alarmLevel != value)
{
this._alarmLevel = value;
NotifyPropertyChanged("AlarmLevel");
}

You should only raise the INotifyPropertyChanged when the value actually changes. When you use INotifyPropertyChanged, the change check is your responsibility. When you you dependency properties, the WPF framework does the check for you.

That's why your code is half working :).