views:

466

answers:

2

Hi,

I have a user control which displays the currently logged in user's name. I have bound a TextBlock in the control to the UserId property of a User obejct in my application.

The issue I have is that the User object my binding has as a source changes each time a new user logs in.

I can think of a solution where I fire an event when the User obejct changes and this is caught my by control which then reinitialise's the binding but this seems less than ideal.

Are there a solution to this issue, I feel it must be very common?

Cheers,

James

+5  A: 

Most UI bindings already handle this via property notifications, in particular (for WPF) INotifyPropertyChanged. - i.e. if you are updating the UserId on a single instance:

class User : INotifyPropertyChanged {
   public event PropertyChangedEventHandler PropertyChanged;
   protected virtual void OnPropertyChanged(string propertyName) {
      PropertyChangedEventHandler handler = PropertyChanged;
      if(handler!=null) handler(this, new PropertyChangdEventArgs(
                                            propertyName));
   }
   private string userId;
   public string UserId {
       get {return userId;}
       set {
           if(userId != value) {
              userId = value;
              OnPropertyChanged("UserId");
           }
       }
   }
}

This should then update the binding automatically. If you are, instead, changing the actual user instance, then consider the same trick, but against whatever hosts the user:

public User User {
    get {return user;}
    set {
        if(user != value) {
            user = value;
            OnPropertyChanged("User");
        }
    }
}

And if you are binding to something's "User.UserId", then it should work.

Marc Gravell
A: 

Is your user object implemeting INotifyPropertyChanged ? as this will bubble up the changes. to your bound controls.

76mel