在.net 2.0中,它提供了一個類別:binding class,用來binding控制項與類別之間的值。一般的寫法:
1: ClassA a = new ClassA();
2: Binding bind_ClassA = new Binding("Text",a,"p1",DataSourceUpdateMode.OnValidation, string.Empty);
3: ultraTextEditor1.DataBindings.Add(bind_ClassA);上述的程式碼,它的效果只會發生在一種情況 - 當使用者變更ultraTextEditor1中的值時,會同步更新至 a物件的p1屬性上。但是,當a.p1的值改變時,它是不會同步至ultraTextEditor1 控制項上的。
那我們要如何達到,當a.p1屬性變更時同步更新在畫面上的ultraTextEditor1上呢?
首先,ClassA必須實作INotifyProperptyChanged介面,使得a.p1值改變時會發出一個propertychanged 事件,當畫面的程式碼收到這個事件時,再將改變後的值同步至ultraTextEditor1上。詳細程式碼,如下:
ClassA.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace Binding自訂屬性
{
public class ClassA : INotifyPropertyChanged
{
private string m_p1;
[Browsable(true)]
[Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
[Category("自訂屬性")]
public string p1
{
get { return m_p1; }
set
{
if (m_p1 != value)
{
m_p1 = value;
NotifyPropertyChanged("p1");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Binding自訂屬性
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ClassA a = new ClassA();
Binding bind_ClassA = null;
private void Form1_Load(object sender, EventArgs e)
{
a.PropertyChanged += new PropertyChangedEventHandler(a_PropertyChanged);
bind_ClassA = new Binding("Text",a,"p1",false, DataSourceUpdateMode.OnValidation,string.Empty);
ultraTextEditor1.DataBindings.Add(bind_ClassA);
bind_ClassA.ControlUpdateMode = ControlUpdateMode.OnPropertyChanged;
a.p1 = "ccc";
}
void a_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
bind_ClassA.ReadValue();
}
private void ultraButton1_Click(object sender, EventArgs e)
{
//bind_ClassA.BindingManagerBase.SuspendBinding();
a.p1 = System.DateTime.Now.ToLongTimeString();
//bind_ClassA.BindingManagerBase.ResumeBinding();
//bind_ClassA.ReadValue();
}
private void ultraButton2_Click(object sender, EventArgs e)
{
MessageBox.Show("p1 = " + a.p1);
MessageBox.Show("TextBox.Value = " + ultraTextEditor1.Value.ToString());
MessageBox.Show("TextBox.Text = " + ultraTextEditor1.Text.ToString());
}
}
}