数据绑定到自定义对象

时间:2012-03-09 18:46:05

标签: c# wpf data-binding

我有一个简单的自定义类(Person),我想将它作为一个整体绑定到一个标签(不要分离这个类的属性)。标签应该只显示Person.ToString()返回的内容(在本例中为FirstName + LastName)。

  1. 如何使用此人作为来源正确绑定它。
  2. 如何确保人物的某个属性的任何更改都会反映在标签中?

  3. 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 个答案:

答案 0 :(得分:3)

创建一个新属性FullName,该属性返回全名,并在PropertyChangedFullName的设置者中为FirstName引发LastName。你永远不应该绑定到对象本身。