c# - 我可以使用数据绑定(bind)格式化事件来有条件地检查复选框吗?

标签 c# winforms data-binding formatting

有关格式化数据绑定(bind)控件的信息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;
}

最佳答案

除了 Binding.Format 事件之外,还有一个 Binding.Parse 事件可用于反转信息。

每个单选按钮都需要自己的数据绑定(bind)设置:

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");
}

关于c# - 我可以使用数据绑定(bind)格式化事件来有条件地检查复选框吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10641552/

相关文章:

c# - 前台线程与后台线程

c# - 如何在Windows窗体中打开app.config?

c++ - 在 winform 中使用 DrawImage

c# - 动态绑定(bind)——根据列解析属性名

javascript - 如何在 KnockoutJS 中用 {{}} 样式绑定(bind)替换 data-bind 标签?

c# - 具有 MVVM 数据绑定(bind)的 session /事务管理 NHibernate

c# - RIA 服务不返回包含的类型集合属性

c# - 在网络浏览器控件中打印谷歌地图 - 不会显示方向线

c# - 在 C# 中从 stdout 和 stderr 重定向输出时保留颜色

c# - 如何设置对公共(public) Elastic Transcoder Amazon SDK 的权限