Custom Binding with INotifyPropertyChanged Interface
Introduction
In this post, I would like to show a simple example of using the INotifyPropertyChanged
interface for binding custom object properties to WinForms controls.
According to Microsoft's documentation, the INotifyPropertyChanged
interface is used to notify clients about property value changes.
The idea underneath is very simple: implementing this interface forces raising the PropertyChange
event, which in-turn notifies the client that the bound property has changed.
An Example
Let's start with building a simple BankAccount
class:
public class BankAccount : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private decimal m_Balance;
private decimal m_CreditLimit;
public BankAccount(decimal initialBalance)
{
this.m_Balance = initialBalance;
this.m_CreditLimit = initialBalance * 2;
}
public decimal Balance
{
get { return m_Balance; }
}
public decimal CreditLimit
{
get { return m_CreditLimit; }
}
public void Withdrawal(decimal sum)
{
if (sum <= m_Balance)
{
m_Balance -= sum;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("Balance"));
}
}
}
public void Deposit(decimal sum)
{
if (sum > 0)
{
m_Balance += sum;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("Balance"));
}
if(m_Balance >= m_CreditLimit)
{
m_CreditLimit = m_Balance * 2;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("CreditLimit"));
}
}
}
}
}
The class contains two properties "Balance
" and "CreditLimit
" which are going to be bound to our simple UI elements:
Here is code demonstrating how we actually bind it:
public partial class MainForm : Form
{
private BankAccount m_Account;
public MainForm()
{
InitializeComponent();
m_Account = new BankAccount(1000);
BindControls();
}
private void BindControls()
{
txtBalance.DataBindings.Add("Text",
m_Account,
"Balance",
true,
DataSourceUpdateMode.OnPropertyChanged);
txtCreditLimit.DataBindings.Add("Text",
m_Account,
"CreditLimit",
true,
DataSourceUpdateMode.OnPropertyChanged);
}
private void btnWithdrawal_Click(object sender, EventArgs e)
{
m_Account.Withdrawal(decimal.Parse(txtSum.Text));
}
private void btnDeposit_Click(object sender, EventArgs e)
{
m_Account.Deposit(decimal.Parse(txtSum.Text));
}
}
Now, the bound textboxes will automatically reflect changes of the "Balance
" and "CreditLimit
" properties after calling the Withdrawal
/Deposit
methods:
The working example could be downloaded here.
This is it.
发表评论
sb06CK Major thanks for the article post.Thanks Again. Cool.