首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获得ListBox的对象?

如何获得ListBox的对象?
EN

Stack Overflow用户
提问于 2021-12-05 16:51:26
回答 2查看 215关注 0票数 -1

我正在尝试从ListBox中获取对象,但是ListBox.Items只返回String,然后我想检查该项目是否被鼠标光标聚焦,我如何做到这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-05 20:26:51

克莱门斯帮助我达成了以下解决方案:

解决方案:

项目= CType((mySender.ItemContainerGenerator.ContainerFromIndex(myVar)),ListBoxItem)

mySender是您的ListBox,myVar是您的整数。

票数 0
EN

Stack Overflow用户

发布于 2021-12-05 17:35:34

您有一个处理程序,它迭代ListBox项:

代码语言:javascript
运行
复制
Private Sub ListBox_PreviewMouseLeftButtonDown(sender As Object, e As MouseButtonEventArgs) Handles listBox.PreviewMouseLeftButtonDown

    Dim mySender As ListBox = sender
    Dim item As ListBoxItem

    For Each item In mySender.Items

        If item.IsFocused Then
            MsgBox(item.ToString)
        End If

    Next

End Sub

您可以添加类似的项(例如,Strings):

代码语言:javascript
运行
复制
Private Sub OnWindowLoad(sender As Object, e As RoutedEventArgs)

    listBox.Items.Add("Item1")
    listBox.Items.Add("Item2")
    listBox.Items.Add("Item3")

End Sub

或者像ListBoxItems

代码语言:javascript
运行
复制
Private Sub OnWindowLoad(sender As Object, e As RoutedEventArgs)

    listBox.Items.Add(New ListBoxItem With { .Content = "Item1" })
    listBox.Items.Add(New ListBoxItem With { .Content = "Item2" })
    listBox.Items.Add(New ListBoxItem With { .Content = "Item3" })

End Sub

首先(当添加字符串时)-处理程序将抛出关于未能将String转换为ListBoxItem的异常,因为您显式地声明了Dim item As ListBoxItem。第二种方式--不会出现强制转换异常,因为您不是添加String,而是添加ListBoxItem.Content of String

显然,您可以声明它为Dim item As String来使事情正常工作,但是String不具有IsFocused属性,您可以使用它来显示消息框。

即使您将数组或字符串列表设置为ItemsSource of您的ListBox -它也会导致异常。但是数组或ListBoxItems列表(设置为ItemsSource )在处理程序中会很好地工作。

因此,答案是mySender.Items不是ListBoxItem的集合,您试图对其进行转换和迭代。您应该将ItemsSource重新定义为ListBoxItems的集合,或者将迭代项的类型从Dim item As ListBoxItem更改为Dim item As String,然后丢失IsFocused属性。

您还可以只使用SelectedItem,而无需迭代和检查IsFocused,也可以使用带TryCast的安全强制转换,检查条目是否为ListBoxItem,或者只使用SelectedItem本身,并在其上调用ToString:

代码语言:javascript
运行
复制
Dim mySender As ListBox = sender
Dim item

If mySender.SelectedItem IsNot Nothing Then
    item = TryCast(mySender.SelectedItem, ListBoxItem)

    If item Is Nothing Then
        item = mySender.SelectedItem
    End If

    MsgBox(item.ToString)

End If
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70236475

复制
相关文章

相似问题

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