WPF中ListView 用鼠标选了其中一行,怎么知道选的是第几行啊。

如题wpf中的~~求教
2025-01-03 19:58:03
推荐回答(1个)
回答1:

刚好解决了此问题.
以下是 VB Source Code:

Imports System.Windows

Public Sub ListView_GetCurrentItemInfo( _
ByVal pListview As Controls.ListView, _
ByVal e As UIElement, _
Optional ByRef dwRowIndex As Integer = Nothing, _
Optional ByRef dwCellIndex As Integer = Nothing)

Dim rowIndex As Integer = -1, cellIndex As Integer = -1
Dim pCP As Controls.ContentPresenter
Dim xCP As DependencyObject

xCP = Media.VisualTreeHelper.GetParent(e)
If xCP Is Nothing Then GoTo FinalStep
pCP = TryCast(xCP, Controls.ContentPresenter)
Do While pCP Is Nothing
xCP = Media.VisualTreeHelper.GetParent(xCP)
pCP = TryCast(xCP,Controls.ContentPresenter)
Loop
rowIndex = pListview.Items.IndexOf(pCP.Content)
Dim pRP As Controls.GridViewRowPresenter
xCP = Media.VisualTreeHelper.GetParent(pCP)
If xCP Is Nothing Then GoTo FinalStep
pRP = TryCast(xCP, Controls.GridViewRowPresenter)
Do While pRP Is Nothing
xCP = Media.VisualTreeHelper.GetParent(xCP)
pRP = TryCast(xCP, Controls.GridViewRowPresenter)
Loop
For i As Integer = 0 To Media.VisualTreeHelper.GetChildrenCount(pRP) - 1
If Media.VisualTreeHelper.GetChild(pRP, i) Is pCP Then
cellIndex = i
GoTo FinalStep
End If
Next
FinalStep:
dwRowIndex = rowIndex
dwCellIndex = cellIndex
End Sub

dwRowIndex 返回的是行.
dwCellIndex 返回的是列.
上述代码当 ListView 的 Cell 为单个 Control 或者直接是 ContentPresenter 时通过测试, 其他情形未作测试.

下面是 ListView (x:Name=lv) 单击鼠标的事件:

Private Sub lvClick(ByVal sender As Object, ByVal e As Input.MouseEventArgs) Handles lv.MouseLeftButtonDown
Dim dwRow, dwCell As Integer
ListView.GetCurrentItemInfo(lv, DirectCast(e.OriginalSource, UIElement), dwRow, dwCell)
...
End Sub

-------------
如果需要 C# 的Code
可以参考一下这个文章:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a52c0d07-76e5-4e6a-8987-5f0eec637939