简体   繁体   中英

Join two string properties (firstName + lastName) of usercontrol and assign it to label

I made a custom usercontrol which contains a label. I have 3 string properties : firstName, lastName, fullName.

How can I set the label's text = FullName ?

    public string firstName
    {
        get; set;
    }

    public string lastName
    {
        get; set;
    }

     public string fullName //this fails
    {

        get { return string.Format("{0} {1}", firstName, lastName); }
        set { labelFullName.Text = value; }
    }

Looks like Windows Form to me. In WPF you would be using labelFullName.Content property. Assuming you want to set the label as the fullname each time first name or last name changes, then one option would be to do this within your UserControl class:

private String _sFirstName = "";
private String _sLastName = "";

public String FirstName { 
  get { return _sFirstName; }
  set { _sFirstName = value; UpdateLabel(); }
}
public String LastName { 
  get { return _sLastName; }
  set { _sLastName = value; UpdateLabel(); }
}
public String FullName {
  get { return _sFirstName + " " + _sLastName; }
}
private void UpdateLabel() {
  // do within a UI thread to prevent threading issues
  this.BeginInvoke((Action)(() => {
    labelFullName.Text = this.FullName.Trim();
  }));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM