我有一个链接到自定义对象集合的数据绑定ComboBox ...
Public Property printerlist As New ObservableCollection(Of Printers)
[..]
Dim PrintersList = New List(Of Printers)
'WMI Stuff
Dim objMS As System.Management.ManagementScope = New System.Management.ManagementScope(ManagementPath.DefaultPath)
objMS.Connect()
'Query Printers
Dim objquery As SelectQuery = New SelectQuery("SELECT * FROM Win32_Printer")
Dim objMOS As ManagementObjectSearcher = New ManagementObjectSearcher(objMS, objquery)
Dim objMOC As System.Management.ManagementObjectCollection = objMOS.Get()
Try
For Each Printers As ManagementObject In objMOC
If CBool(Printers("Local")) Then
PrintersList.Add(New Printers With {.DeviceName = Printers("Name"), .Type = "Local"})
End If
If CBool(Printers("Network")) Then
PrintersList.Add(New Printers With {.DeviceName = Printers("Name"), .Type = "Network"})
End If
Next
Catch ex As Exception
Debug.Print(ex.Message)
End Try
Dim LCV As ListCollectionView = New ListCollectionView(PrintersList)
Printer_Select.ItemsSource = LCV
[..]
Public Class Printers
Public Property DeviceName As String
Public Property Type As String
End Class<ComboBox x:Name="Printer_Select" Background="{x:Null}" Padding="4,5,4,3" BorderBrush="Gainsboro" >
<ComboBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" FontWeight="Bold" FontSize="11" FontFamily="Segoe UI Semibold"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ComboBox.GroupStyle>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DeviceName}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>当我试图检索ComboBox 'Printer_Select‘的SelectedItem时,得到的要么是元素的名称,要么是错误’从类型'Printers‘到类型'String’的转换无效。
在下拉列表中被选中时,如何获取ComboBoxItem的DeviceName?
发布于 2019-05-20 21:34:14
将SelectedItem强制转换为Printers对象:
Dim selectedPrinter As Printers = TryCast(Printer_Select.SelectedItem, Printers)
If selectedPrinter IsNot Nothing Then
Dim deviceName As String = selectedPrinter.DeviceName
'...
End Ifhttps://stackoverflow.com/questions/56221847
复制相似问题