从DataBound组合框中读取SelectedItem

时间:2019-05-20 13:20:45

标签: wpf vb.net data-binding

我有一个绑定到自定义对象集合的数据绑定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>

当我尝试检索SelectedItem'Printer_Select'的ComboBox时,我得到了元素的名称,或者不是从类型'Printers'到类型'String'的错误'Conversion有效。'

在下拉列表中选择DeviceName的{​​{1}}时如何获得?

1 个答案:

答案 0 :(得分:1)

SelectedItem投射为Printers对象:

Dim selectedPrinter As Printers = TryCast(Printer_Select.SelectedItem, Printers)
If selectedPrinter IsNot Nothing Then
    Dim deviceName As String = selectedPrinter.DeviceName
    '...
End If
相关问题