0

我有两个问题:

首先,我正在努力将一些 WMI 对象添加到字典中。目前,每当我尝试添加所需的值时,我都会得到System.InvalidCastException: Specified cast is not valid.如何纠正这个问题?

其次,将这些 WMI 对象/值添加到我的字典后,如何将我的字典绑定到 WPF 组合框?我希望能够绑定字典值,在这种情况下绑定NetConnectionID到组合框下拉列表,同时在Index选择对应值时从我的字典中返回。

这是我的代码:

class NetworkInterfaces
{
    public Dictionary<int, string> GetNetworkAdapters()
    {
        Dictionary<int, string> Adapters = new Dictionary<int, string>(); 

        try
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher
                ("SELECT Index,NetConnectionID FROM Win32_NetworkAdapter");
            ManagementObjectCollection data = searcher.Get();
            foreach (ManagementObject item in data)
                Adapters.Add((int)item["Index"], (string)item["NetConnectionID"]);

            return Adapters;
        }
        catch (Exception ex)
        {
            Console.WriteLine("ERROR: " + ex);
        }

        return null;
    }
}

. . . .

    private void NetworkAdapters()
    {
        NetworkInterfaces NICInfo = new NetworkInterfaces();
        Dictionary<int, string> Adapters = NICInfo.GetNetworkAdapters();

        if (Adapters != null)
        {                
            cmbNetworkAdapters.ItemsSource = Adapters;
            cmbNetworkAdapters.DisplayMemberPath = "Value";
        }
    }

    private void cmbNetworkAdapters_DropDownOpened(object sender, EventArgs e)
    {
        cmbNetworkAdapters.DisplayMemberPath = "Key";
    }

    private void cmbNetworkAdapters_DropDownClosed(object sender, EventArgs e)
    {
        cmbNetworkAdapters.DisplayMemberPath = "Value";
    }

错误详情:

System.InvalidCastException was caught
  HResult=-2147467262
  Message=Specified cast is not valid.
  Source=MyProject
  StackTrace:
       at MyProject.NetworkInterfaces.GetNetworkAdapters() in h:\_Storage\Projects\MyProject\MyProject\NetworkInterfaces.cs:line 28
  InnerException: 
4

0 回答 0