我有一个combobox
列出了一些单字节cmds,可以发送给我开发的一些自定义硬件。使用下面的C#代码,用户当前只能通过名称从cbCANcmd
中选择命令。我还找到了仅显示值的方法,但更喜欢同时显示名称和数字。
cmd
?例如0d - CommsSoftReset
un-enumerated
值,例如05
?09-WipeAllFlash
),但仍按照上述#2数字输入它们吗?注意:枚举来自直接的C语言.h文件,并且标头每天更改的次数比c#app更多。出于这个原因,我希望避免为每个值添加[Description()]
,或者大幅更改格式,因为在我们继续开发时必须多次复制和重做
P.S。我通常只用简单的C编写,8bit micro接收这些命令。由于这是我在c#中的第一个测试应用程序,请温柔:)
enum COMMS_MESSAGE_ID_t : byte
{
CommsRAMRead = 0x00,
CommsRAMWrite = 0x01,
CommsCommitRAMbufferToFlash = 0x02,
CommsWipeAllFlash = 0x0c,
CommsSoftReset = 0x0d,
CommsGetVersion = 0xff
}
private void SendTab_Enter(object sender, EventArgs e)
{
//need to populate the pulldowns with the available commands
cbCANcmd.DataSource = Enum.GetValues(typeof(COMMS_MESSAGE_ID_t));
}
private void SendDownlinkCmd_Click(object sender, EventArgs e)
{
// send the command selected in the send tab's combobox
byte CANcmd = (byte)(COMMS_MESSAGE_ID_t)cbCANcmd.SelectedValue;//first byte
}
答案 0 :(得分:1)
如果这是一个WinForms应用程序,这里是#1的可能解决方案。如果这样做,我们可以继续前进。
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
foreach (var val in Enum.GetNames(typeof(COMMS_MESSAGE_ID_t)))
{
cbCANcmd.Items.Add(new CommsMessage(val));
}
}
}
public class CommsMessage
{
public string Name { get; set; }
public COMMS_MESSAGE_ID_t Message { get; set; }
public CommsMessage(string msgName)
{
Name = msgName;
Message = (COMMS_MESSAGE_ID_t)Enum.Parse(typeof (COMMS_MESSAGE_ID_t), msgName);
}
public override string ToString()
{
return string.Format("{0:x} - {1}", Message, Name);
}
}
然后,只要你获得ComboBox.SelectedItem的值,就可以执行以下操作:
COMMS_MESSAGE_ID_t msg = (cbCANcmd.SelectedItem as CommsMessage).Message;
我遗漏了很多你应该做的异常处理,但我希望这会有所帮助。