2

此处有关格式化数据绑定控件的信息是否有一种非笨拙的方式来使用绑定数据执行特殊情况格式化?是很棒的。

现在,如果我想有条件地检查复选框怎么办 - 有没有办法使用格式化事件来完成它?目前我的代码是:

// 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;
}
4

1 回答 1

4

除了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");
}
于 2012-05-17T19:03:08.133 回答