我有一个简单的自定义类(Person),我想将它作为一个整体绑定到一个标签(不要分离这个类的属性)。标签应该只显示Person.ToString()
返回的内容(在本例中为FirstName + LastName)。
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}"
答案 0 :(得分:3)
创建一个新属性FullName
,该属性返回全名,并在PropertyChanged
和FullName
的设置者中为FirstName
引发LastName
。你永远不应该绑定到对象本身。