Question

Let's say I have a property called Greeting that is principally composed of two bound properties: LastName and FirstName. Can I subscribe to updates on first and last name so I can force a refresh with OnPropertyChanged() for my Greeting property. Here's a simple example:

View

<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
<TextBlock Text="{Binding Greeting}" />

ViewModel

Public Property FirstName() As String
    Get
        Return _firstName
    End Get
    Set(ByVal value As String)
        _firstName = value
        OnPropertyChanged("FirstName")
    End Set
End Property

'... Omitting LastName for brevity ...

Public ReadOnly Property Greeting() As String
    Get
        Return String.Format("Hello {0} {1}", Firstname, LastName)
    End Get
End Property

The way this is currently set up, nothing will ever update the Greeting binding. I could put OnPropertyChanged("Greeting") in the setter for FirstName and LastName, but this feels wrong. In a more complex example, I'd rather each object just take care of refreshing itself when something changes.

Q:) Can I force an update for a ReadOnly Property when one of the Properties it's composed of changes?

Was it helpful?

Solution

You can call PropertyChange of Greetings from setter of FirstName and LastName

Public Property FirstName() As String
    Get
        Return _firstName
    End Get
    Set(ByVal value As String)
        _firstName = value
        OnPropertyChanged("FirstName")
        OnPropertyChanged("Greeting")
    End Set
End Property

OR

You can subscribe to PropertyChanged of your ViewModel in itself

AddHandler this.PropertyChanged, AddressOf PropertyChanged

and in PropertyChanged you can check which property is changed depending on that you can RaisePropertyChanged for Greeting

OTHER TIPS

Borrowing from nit's answer, just to round it out a little. Here's what I did to fire an update on the Greeting property when FirstName or LastName changes:

Private Sub UpdateGreeting(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) _
    Handles Me.PropertyChanged
    If e.PropertyName = "FirstName" OrElse e.PropertyName="LastName" Then
        OnPropertyChanged("Greeting")
    End If
End Sub
  • It handles the PropertyChanged event that is already implemented as part of the INotifyPropertyChanged interface on the ViewModel.
  • Then it checks if the PropertyName value of the event argument is equal to "FirstName" or "LastName".
  • If so, it manually raises the OnPropertyChanged() method for the Greeting property.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top