我有两个问题:
首先,我正在努力将一些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: