问题描述
我有一个具有几个属性的对象,其中一个是 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.
我将使表单实现
并使用单选按钮事件来提高事件
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!