我在试用项目中玩DataBinding有点困难。我有一个简单的表单只有一个spinbox,我想绑定到表单的成员。
class Form1 {
public class Data : System.ComponentModel.INotifyPropertyChanged {
int _value = 10;
public int value {get;set;}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
public Data data; // the member I want to bind to
}
在VS IDE中,我的旋转属性框中的数据部分允许我选择Form1.data作为数据源,但是
我无法忍受这一点。有什么想法吗?
答案 0 :(得分:1)
对于object =>控件更新:您的事件不会被引发 - 自动实现的属性不关心INotifyPropertyChanged
- 您需要将其移出:
public class Data : INotifyPropertyChanged {
int _value = 10;
public int Value {
get {return _value;}
set {
if(value != _value) {
_value = value;
OnPropertyChanged("Value");
}
}
}
protected virtual void OnPropertyChanged(string propertyName) {
var handler = PropertyChanged;
if(handler != null) {
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
但是对于另一个(control =>对象),我希望你没有正确的绑定设置。您应该绑定到Data.Value
属性,并且您需要在运行时告诉它Data
实例:
someBindingSource.DataSource = data;
或者如果您直接使用DataBindings
- 以下显示它使用上述类型:
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Data data = new Data();
data.PropertyChanged += delegate {
Debug.WriteLine("Value changed: " + data.Value);
};
Button btn;
NumericUpDown nud;
Form form = new Form {
Controls = {
(nud = new NumericUpDown()),
(btn = new Button {
Text = "Obj->Control",
Dock = DockStyle.Bottom })
}
};
nud.DataBindings.Add("Value", data, "Value",
false, DataSourceUpdateMode.OnPropertyChanged);
btn.Click += delegate { data.Value++; };
Application.Run(form);
}
}