首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从DataBound组合框读取SelectedItem

从DataBound组合框读取SelectedItem
EN

Stack Overflow用户
提问于 2019-05-20 21:20:45
回答 1查看 30关注 0票数 0

我有一个链接到自定义对象集合的数据绑定ComboBox ...

代码语言:javascript
复制
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
代码语言:javascript
复制
<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’的转换无效。

在下拉列表中被选中时,如何获取ComboBoxItemDeviceName

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-20 21:34:14

SelectedItem强制转换为Printers对象:

代码语言:javascript
复制
Dim selectedPrinter As Printers = TryCast(Printer_Select.SelectedItem, Printers)
If selectedPrinter IsNot Nothing Then
    Dim deviceName As String = selectedPrinter.DeviceName
    '...
End If
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56221847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档