6

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

2
  • Is it the User object that changes (if so, where is it set?) or is it the UserId that changes (on the same User instance)? Commented May 8, 2009 at 10:16
  • If the DataSource is changing, Setting the DataSource to the new object should automatically update bound controls. If a bound property is changing.. you need INotifyPropertyChanged Commented May 8, 2009 at 12:30

1 Answer 1

8

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 PropertyChangedEventArgs(
                                            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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.