这里有两种可能的解决方案。
绑定格式和解析事件
The Binding
类有一个内置工具,用于以以下形式即时转换绑定数据Format http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx and Parse http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.parse.aspx events.
以下是您如何仅通过“男性”单选按钮来使用这些事件。在代码中而不是在设计器中创建绑定:
// create binding between "Sex" property and RadioButton.Checked property
var maleBinding = new Binding("Checked", bindingSource1, "Sex");
// when Formatting (reading from datasource), return true for M, else false
maleBinding.Format += (s, args) => args.Value = ((string)args.Value) == "M";
// when Parsing (writing to datasource), return "M" for true, else "F"
maleBinding.Parse += (s, args) => args.Value = (bool)args.Value ? "M" : "F";
// add the binding
maleRb.DataBindings.Add(maleBinding);
// you don't need to bind the Female radiobutton, just make it do the opposite
// of Male by handling the CheckedChanged event on Male:
maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;
计算属性
另一种方法是将计算属性添加到数据源:
public bool IsMale
{
get { return Sex == "M"; }
set
{
if (value)
Sex = "M";
else
Sex = "F";
}
}
现在,您可以简单地将 Male 单选按钮绑定到数据源上的此属性(只是不在网格中显示此属性)。
您可以再次将女性连接到男性,如下所示:
maleRb.CheckedChanged += (s, args) => femaleRb.Checked = !maleRb.Checked;