0

I have a simple custom class (Person), which I want to bind to a label as a whole (not to separate properties of this class). The label should just present whatever the Person.ToString() returns (in this case FirstName + LastName).

  1. How do I properly bind it using the person as a Source.
  2. How do I make sure that any change in one of the properties of the Person will be reflected in the label?

public class Person : INotifyPropertyChanged {
    private string firstName;
    public string FirstName {
        get { 
           return firstName; 
        }

        set {
            firstName = value;
            OnPropertyChanged("FirstName");
        }
    }

    private string lastName;

    public string LastName {
        get { 
            return lastName; 
        }

        set {
            lastName = value;
            OnPropertyChanged("LastName");
        }
    }

    public override string ToString() {           
        return FirstName + " " + LastName;
    }

    private void OnPropertyChanged(string name) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

public Window1() {
myPerson = new Person() {
    FirstName = "AAA",
        LastName = "BBB"};

    InitializeComponent();
}

public Person MyPerson  {
    get { 
        return myPerson; 
    }

    set { 
        myPerson = value; 
    }
}

Label Content="{Binding Source=MyPerson}"
1
  • By the way, Source=MyPerson sets the binding source to the string "MyPerson". Commented Mar 9, 2012 at 19:29

1 Answer 1

3

Create a new property FullName which returns the full name and raise PropertyChanged for FullName in the setters of FirstName and LastName as well. You should never bind to the object itself.

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

1 Comment

Agree with H.B. You can actually bind to the object it self, but you won't get change notifications.

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.