界面上有两个radioButton,一个是男,一个是女,但是实体类里只有一个int类型的Sex属性,Sex==1是男,Sex==0是女,现在需要把这两个控件绑定到Sex属性,可以这样实现:
1 先把这两个radioButton抽出来放到一个UserControl里,实现INotifyPropertyChanged接口,两个radioButton的CheckChanged的事件调用同一个委托PropertyChanged
代码如下:
public partial class TestNotifyChangeUserControl : UserControl, INotifyPropertyChanged
{
public TestNotifyChangeUserControl()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyChange(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private void btnMan_CheckedChanged(object sender, EventArgs e)
{
NotifyChange("Sex");
}
public int Sex
{
get
{
if (this.btnMan.Checked)
{
return 1;
}
else
{
return 0;
}
}
set
{
if (value == 1)
{
this.btnMan.Checked = true;
this.btnWoman.Checked = false;
}
else
{
this.btnWoman.Checked = true;
this.btnMan.Checked = false;
}
}
}
}
2 重新编译后把这个UserControl拖到另一个Form上,在这个Form里直接绑定UserControl里的Sex属性,代码如下:
public partial class Form3 : Form
{
BindingList<User> userList = new BindingList<User>();
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
User user = new User();
user.Id = 1;
user.Name = "jam";
user.Sex = 0;
userList.Add(user);
this.testNotifyChangeUserControl1.DataBindings.Add("Sex",userList,"Sex");
}
private void btn_Click(object sender, EventArgs e)
{
MessageBox.Show(userList[0].Sex.ToString());
}
}