string
您需要为每个端口创建一个列表,而不是向菜单中添加一个列表MenuItem
,并为该项目注册一个单击事件,然后将其添加到主菜单中。将您的代码更改为:
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
MenuItem menuItem = new MenuItem { Header = port };
menuItem.Click += new RoutedEventHandler(Menu_Port_Click);
Menu_Port.Items.Add(menuItem);
}
然后添加一个事件处理方法来从菜单项(即端口)中获取文本:
private void Menu_Port_Click(object sender, RoutedEventArgs e)
{
string selectedPort = ((MenuItem)sender).Header.ToString();
// Alternatively, if you want to maintain a list of selected ports, you can do something like this:
MenuItem selectedMenu = ((MenuItem)sender);
if (selectedMenu.IsChecked)
{
// In this case "allSelectedPorts" is a global string list.
allSelectedPorts.Add(selectedMenu.Header.ToString());
}
else
{
allSelectedPorts.Remove(selectedMenu.Header.ToString());
}
}
编辑
如果您希望一次只选择一个菜单项,您可以执行以下操作:
string selectedPort = string.Empty;
private void Menu_Port_Click(object sender, RoutedEventArgs e)
{
MenuItem selectedMenu = ((MenuItem)sender);
Menu_Port.Items.Cast<MenuItem>().Where(
menu => menu != selectedMenu).ToList().ForEach(item => item.IsChecked = false);
if (selectedMenu.IsChecked)
{
selectedPort = selectedMenu.Header.ToString();
}
else
{
selectedPort = string.Empty;
}
}