【发布时间】:2011-03-10 19:33:19
【问题描述】:
我正在尝试将一些 RadioButtons 绑定到一个类中的布尔值,从而启用/禁用表单上的其他元素。例如:
x radioButton1
x checkBox1
x radioButton2
x checkBox2
我只想在选择 radioButton1 时启用 checkBox1,对于 radioButton2 和 checkBox2 也是如此。
当我尝试绑定这些时,需要单击两次才能更改 RadioButton 选择。似乎绑定的顺序导致了逻辑问题。
这是显示这一点的代码。该表单只是两个默认命名的 RadioButtons 和两个 CheckBoxes。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
BindingSource bindingSource = new BindingSource(new Model(), "");
radioButton1.DataBindings.Add(new Binding("Checked", bindingSource, "rb1Checked", true, DataSourceUpdateMode.OnPropertyChanged));
radioButton2.DataBindings.Add(new Binding("Checked", bindingSource, "rb2Checked", true, DataSourceUpdateMode.OnPropertyChanged));
checkBox1.DataBindings.Add(new Binding("Enabled", bindingSource, "cb1Enabled", true, DataSourceUpdateMode.OnPropertyChanged));
checkBox2.DataBindings.Add(new Binding("Enabled", bindingSource, "cb2Enabled", true, DataSourceUpdateMode.OnPropertyChanged));
}
}
public class Model : INotifyPropertyChanged
{
private bool m_rb1Checked;
public bool rb1Checked
{
get { return m_rb1Checked; }
set
{
m_rb1Checked = value;
NotifyPropertyChanged("cb1Enabled");
}
}
private bool m_rb2Checked;
public bool rb2Checked
{
get { return m_rb2Checked; }
set
{
m_rb2Checked = value;
NotifyPropertyChanged("cb2Enabled");
}
}
public bool cb1Enabled { get { return rb1Checked; } }
public bool cb2Enabled { get { return rb2Checked; } }
public Model()
{
rb1Checked = true;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string fieldName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(fieldName));
}
}
#endregion
}
有人知道如何实现这项工作吗?
【问题讨论】: