Wednesday, August 15, 2012

Coerce Value in Property Setter - Silverlight 5

Coerce Value in Property Setter - Silverlight 5

In the example below, we have bound a ViewModel to a view with a single property called Message. This property is bound to a TextBox with a two way binding. For this test, we're doing some value coercion in the setter and raising the property changed again.

In Silverlight 4, this worked perfectly. If the message property changed in the property setter, the textbox would see the new value. E.g. typing "A" into the textbox and losing focus would result in Aaaaaaaaaaa appearing as the value was changed.

In Silverlight 5 however, this seems to be broken/changed. The getter is never hit after the value is modified in the setter. Adding a IValueConverter in between, shows that the Convert/ConvertBack methods are never hit. It seems that something fundamental has changed between version 4 and 5. Has there been any changes? Is this a bug?

public class ViewModel : INotifyPropertyChanged {     private string _message;      public event PropertyChangedEventHandler PropertyChanged;      public string Message     {         get         {             return _message;          }         set         {             _message = value;             this.RaisePropertyChanged();              if (_message.Length < 10)             {                 _message = _message.PadRight(10, 'a');                 this.RaisePropertyChanged();             }         }     }      private void RaisePropertyChanged()     {         var handler = this.PropertyChanged;         if (handler != null)         {             handler(this, new PropertyChangedEventArgs("Message"));         }     } } 

Answers & Comments...




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog