无线电按钮和数据绑定在vb.net [英] Radio Buttons And Databinding in vb.net

查看:104
本文介绍了无线电按钮和数据绑定在vb.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有几个属性的对象,其中一个是 CarpetColor 。我还有三个单选按钮( rbRed rbBlue rbGreen )在自己的容器中的表单上。我想使用数据绑定将对象的 CarpetColor 设置为选中哪个按钮。

I have an object with a few properties, one of which is CarpetColor. I also have three radio buttons (rbRed, rbBlue, rbGreen) on a form within their own container. I want to use databinding to set the object's CarpetColor to whichever button is checked.

我知道如何做一个控件的属性绑定到对象属性的简单绑定。我不知道的是如何将三个控件的结果绑定到一个属性。例如,如果用户点击红色,则 CarpetColor 的值应为红色。同样,如果他选择绿色,那么 CarpetColor 的值应该改为绿色。

I know how to do a simple binding where one control's property binds to an object property. What I can't figure out is how to bind the result of three controls to one property. As an example, if the user clicks 'Red', the value of CarpetColor should be "Red". Similarly, if he chooses 'Green', the value of CarpetColor should change to "Green".

推荐答案

在CarpetColor表单上创建一个属性,如下所示:

Create a property on a form called CarpetColor like this:

enum Color { Red, Blue, Green } 
public Color CarpetColor
{ 
get { return rbGreen.Checked ? Green : (rbRed.Checked ? Red : Blue); }
set 
  {  
    if (value == Green)
        rbGreen.Checked = true;
    else
        if (value == Red)
           rbRed.Checked = true;
        else
           rbBlue.Checked = true;
   }
}

然后你可以简单地绑定CarpetColor属性表单到数据源的CarpetColor。

and then you can simply bind the CarpetColor property on your form to the data source's CarpetColor.

我将使表单实现 INotifyPropertyChanged接口
并使用单选按钮事件来提高 PropertyChanged 事件

protected void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

rbGreen.CheckedChanged += (s, args) => OnPropertyChanged("CarpetColor");
rbRed.CheckedChanged += (s, args) => OnPropertyChanged("CarpetColor");
rbBlue.CheckedChanged += (s, args) => OnPropertyChanged("CarpetColor");

这篇关于无线电按钮和数据绑定在vb.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆