我想将标签绑定到类的属性并尝试这个:
public class Test
{
public string Name { get; set; }
}
Test test = new Test () { Name = "abc" };
label.DataBindings.Add ("Text", test, "Name");
这显示" abc"在标签上。如果在数据绑定后更改Name属性,则标签不会反映新值。怎么了?
答案 0 :(得分:0)
我建议你以其他方式使用绑定。
label.DataBindings.Add(new Binding("Text", test, "Name", false, DataSourceUpdateMode.OnPropertyChanged));
我希望这适合你!
另一种方法是更新您的类以使用值更改事件,
class Test
{
private string name;
public string Name
{
get { return name; }
set
{
//Check if you are assigning the same value
if (Equals(name, value))
return;
name = value;
OnNameChanged();
}
public event EventHandler NameChanged;
protected virtual void OnNameChanged()
{
var handler = NameChanged;
if (handler != null)
handler(this, EventArgs.Empty);
}
}
}
如果第一个不起作用。
最好的解决方案是通用方式,
class Test : INotifyPropertyChanged
{
private string name = "";
public string Name
{
get { return name; }
set { name = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged()
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}