我制作了一个包含标签的自定义用户控件。 我有3个字符串属性:firstName,lastName,fullName。
如何设置标签的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; }
}
答案 0 :(得分:5)
看起来像Windows Form给我。在WPF中,您将使用labelFullName.Content属性。假设您希望每次更改名字或姓氏时将标签设置为全名,那么一个选项就是在UserControl类中执行此操作:
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();
}));
}