【发布时间】:2010-11-23 09:32:42
【问题描述】:
我有一个文本框,我改变了它的左值。并且此 TextBox 绑定到具有 X 属性的类。现在,当我更改 TextBox 的 Left 值时,我希望更新班级的 X。我应该怎么做才能强制更新我的数据绑定类属性?
【问题讨论】:
标签: c# data-binding binding textbox
我有一个文本框,我改变了它的左值。并且此 TextBox 绑定到具有 X 属性的类。现在,当我更改 TextBox 的 Left 值时,我希望更新班级的 X。我应该怎么做才能强制更新我的数据绑定类属性?
【问题讨论】:
标签: c# data-binding binding textbox
由于数据绑定的工作原理,这种类型的 2-way 绑定仅在控件通告更改时才有效;通常通过*Changed 事件 - 在这种情况下即LeftChanged。由于没有这样的事件,你根本不能,除非继承 TextBox,重新声明 (new) Left 并添加一个与 LocationChanged 挂钩的 LeftChanged。
您可以向LocationChanged 添加一个事件并手动执行吗?还是在设置位置/左侧时手动更新对象?
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
class SuperTextBox : TextBox
{
protected override void OnLocationChanged(EventArgs e)
{
base.OnLocationChanged(e);
EventHandler handler = (EventHandler)Events[LeftChangedKey];
if (handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler LeftChanged
{
add { Events.AddHandler(LeftChangedKey, value); }
remove { Events.RemoveHandler(LeftChangedKey, value); }
}
public new int Left
{
get { return base.Left; }
set { base.Left = value; }
}
private static readonly object LeftChangedKey = new object();
}
class Person {
private int value;
public int Value {
get {return value;}
set {
this.value = value;
EventHandler handler = ValueChanged;
if(handler!=null)
{
handler(this, EventArgs.Empty);
}
}
}
public event EventHandler ValueChanged;
}
static class Program
{
static void Main()
{
Button btn;
TextBox txt;
Person p = new Person { Value = 10 };
using (Form form = new Form {
DataBindings = {{ "Text", p, "Value"}},
Controls = {
(txt = new SuperTextBox {
DataBindings = {{ "Left", p, "Value", false,
DataSourceUpdateMode.OnPropertyChanged}}
}),
(btn = new Button {
Text = "bump",
Dock = DockStyle.Bottom
})
}
}) {
btn.Click += delegate { txt.Left += 5; };
Application.Run(form);
}
}
}
}
【讨论】: