Back to Devexpress

Convert to Property with Change Notification/Introduce Change Notification

coderushforroslyn-118442-coding-assistance-code-providers-convert-to-property-with-change-notification-introduce-change-notification.md

latest2.3 KB
Original Source

Convert to Property with Change Notification/Introduce Change Notification

  • Aug 03, 2020
  • 2 minutes to read

Purpose

Introduces change notifications for a property. Use the Code Provider when you need a property to raise an event each time its value changes.

Availability

Available when the caret is on a property, assuming that its parent type implements the INotifyPropertyChanged interface.

Usage

  1. Place the caret on a property declaration.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select Introduce Change Notification from the menu ( Convert to Property with Change Notification if the target property is auto-implemented).

After execution, the Code Provider adds an event invocation statement to the property setter. The Property Changed event is invoked with an event-rising method if the parent type contains such a method. Otherwise, the Code Provider uses the boilerplate event invocation statement.

The Introduce Setter Guard Clause is automatically called for the target property’s setter to prevent the unwanted event invocation in case the new value equals the old one.

csharp
class Person : INotifyPropertyChanged {
    string fullName;
    public string FullName {
        get {
            return fullName;
        }
        set {
            if (fullName == value)
                return;
            fullName = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FullName)));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
vb
Class Person
    Implements INotifyPropertyChanged

    Private _fullName As String
    Public Property FullName() As String
        Get
            Return _fullName
        End Get
        Set(value As String)
            If _fullName Is Value Then
                Return
            End If
            _fullName = value
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(NameOf(FullName)))
        End Set
    End Property

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged
End Class