How can I access the ListViewItems of a WPF ListView?

前端 未结 6 948
天命终不由人
天命终不由人 2020-12-09 10:33

Within an event, I\'d like to put the focus on a specific TextBox within the ListViewItem\'s template. The XAML looks like this:



        
6条回答
  •  猫巷女王i
    2020-12-09 11:36

    We use a similar technique with WPF's new datagrid:

    Private Sub SelectAllText(ByVal cell As DataGridCell)
        If cell IsNot Nothing Then
            Dim txtBox As TextBox= GetVisualChild(Of TextBox)(cell)
            If txtBox IsNot Nothing Then
                txtBox.Focus()
                txtBox.SelectAll()
            End If
        End If
    End Sub
    
    Public Shared Function GetVisualChild(Of T As {Visual, New})(ByVal parent As Visual) As T
        Dim child As T = Nothing
        Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
        For i As Integer = 0 To numVisuals - 1
            Dim v As Visual = TryCast(VisualTreeHelper.GetChild(parent, i), Visual)
            If v IsNot Nothing Then
                child = TryCast(v, T)
                If child Is Nothing Then
                    child = GetVisualChild(Of T)(v)
                Else
                    Exit For
                End If
            End If
        Next
        Return child
    End Function
    

    The technique should be fairly applicable for you, just pass your listviewitem once it's generated.

提交回复
热议问题