C# 将组合框中的选定值绑定到类的成员
我有一个绑定到类实例的组合框。我需要获取组合框的用户选择ID,并设置一个与之相等的类属性 例如,下面是一个类:C# 将组合框中的选定值绑定到类的成员,c#,data-binding,C#,Data Binding,我有一个绑定到类实例的组合框。我需要获取组合框的用户选择ID,并设置一个与之相等的类属性 例如,下面是一个类: public class robot { private string _ID; private string _name; private string _configFile; [XmlElement("hardware")] public hardware[] hardware; public string ID {
public class robot
{
private string _ID;
private string _name;
private string _configFile;
[XmlElement("hardware")]
public hardware[] hardware;
public string ID
{
get { return _ID; }
set { _ID = value; }
}
public string name
{
get { return _name; }
set { _name = value; }
}
public string configFile
{
get { return _configFile; }
set { _configFile = value; }
}
}
下面是将combobox绑定到该类实例的代码。此显示是组合框中阵列中每个机器人的名称
private void SetupDevicesComboBox()
{
robot[] robot = CommConfig.robot;
cmbDevices.DataSource = robot;
cmbDevices.DisplayMember = "name";
cmbDevices.ValueMember = "ID";
}
但现在我似乎无法接受用户的选择并使用它。如何使用用户从组合框中选择的内容的“ID”
Settings.selectedRobotID = cmbDevices.ValueMember; //This just generates "ID" regardless of what is selected.
我也试过了
Settings.selectedRobotID = cmbDevices.SelectedItem.ToString(); //This just generates "CommConfig.robot"
试一试
这很酷,奏效了。我发现这也有效。Settings.selectedRobotID=cmbDevices.SelectedValue.ToString();
Settings.selectedRobotID = ((robot)cmbDevices.SelectedItem).ID;