格式化数据绑定控件的信息Is there a non-klunky way to perform special-case formatting with bound data?非常棒。
现在如果我想有条件地检查复选框怎么办?有没有办法使用格式化事件来完成它?目前我的代码是:
// if gender = "N" Index = -1, if "F", index = 0, if "M" index = 1;
if (platypusInfo.Gender.Equals("F")) {
radioButtonFemale.Checked = true;
radioButtonMale.Checked = false;
} else if (platypusInfo.Gender.Equals("M")) {
radioButtonMale.Checked = true;
radioButtonFemale.Checked = false;
} else { // (platypus.Gender == "N")
radioButtonFemale.Checked = false;
radioButtonMale.Checked = false;
}
答案 0 :(得分:3)
除Binding.Format
事件外,还有一个Binding.Parse
事件可用于撤销信息。
每个单选按钮都需要自己的数据绑定设置:
Binding maleBind = new Binding("Checked", person, "Gender", true);
maleBind.Format += new ConvertEventHandler(maleBind_Format);
maleBind.Parse += new ConvertEventHandler(maleBind_Parse);
radioButtonMale.DataBindings.Add(maleBind);
Binding femaleBind = new Binding("Checked", person, "Gender", true);
femaleBind.Format += new ConvertEventHandler(femaleBind_Format);
femaleBind.Parse += new ConvertEventHandler(femaleBind_Parse);
radioButtonFemale.DataBindings.Add(femaleBind);
然后是事件:
void femaleBind_Parse(object sender, ConvertEventArgs e) {
if ((bool)e.Value)
e.Value = "F";
}
void femaleBind_Format(object sender, ConvertEventArgs e) {
e.Value = ((string)e.Value == "F");
}
void maleBind_Parse(object sender, ConvertEventArgs e) {
if ((bool)e.Value)
e.Value = "M";
}
void maleBind_Format(object sender, ConvertEventArgs e) {
e.Value = ((string)e.Value == "M");
}