0

我在 WPF 应用程序(Framework 3.5 SP1)中的 TreeView 有问题。这是一个具有 2 个数据级别的 TreeVIew。我以特定方式展开/折叠第一级的项目(在 TreeViewItem 上单击鼠标)。同样,当我展开第一级 TreeViewItem 时,我将一些第二级 TreeViewItems 添加到组中(这是一个重要的细节,事实上,如果我不添加项目,问题就不会发生)。一切正常,直到 TreeView 失去焦点。例如,如果我在第一个位置展开 TreeViewItem,同时将一个元素添加到第二级,然后单击一个按钮(让 TreeView 失去焦点),然后再次单击TreeViewItem 在第三个位置展开它,用鼠标位置命中测试产生的 TreeViewItem 不是“真实的” TreeViewItem(在本例中为第三个),但 TreeViewItem 的位置高于单击的那个(在本例中为第二个)。我尝试在 TreeView-LostFocus 事件上使用 UpdateLayout 方法,但没有结果。可能我需要一种相反的方法:从 UI 开始,刷新包含 TreeViewItems 位置的对象。你能帮我么?谢谢!皮莱吉

这是代码:

   ' in this way I tried to put remedy at the problem, but it doesn't work.
    Private Sub tvArt_LostFocus(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles tvArt.LostFocus
        Me.tvArt.UpdateLayout()

        e.Handled = True
    End Sub

    ' here I expand / collapse the items of the first level of my TreeView
    Private Sub tvArt_PreviewMouseUp(ByVal sender As System.Object, ByVal e As MouseButtonEventArgs) Handles tvArt.PreviewMouseUp
        Dim p As Point = Nothing
        Dim tvi As TreeViewItem = getItemFromMousePosition(Of TreeViewItem)(p, e.OriginalSource, Me.tvArt)
        If tvi Is Nothing = False Then
            If tvi.HasItems Then
                Dim be As BindingExpression = BindingOperations.GetBindingExpression(tvi, TreeViewItem.ItemsSourceProperty)
                Dim ri As P_RicambiItem = DirectCast(be.DataItem, P_RicambiItem)
                If ri.isExpanded = False then
                    ' here I add items to the second level collection
                End If

                ri.isExpanded = Not ri.isExpanded
            End If
        End If

        e.Handled = True
    End Sub

    Private Function getItemFromMousePosition(Of childItem As DependencyObject)(ByRef p As Point, ByVal sender As UIElement, _
        ByVal _item As UIElement) As childItem

        p = sender.TranslatePoint(New Point(0, 0), _item)
        Dim obj As DependencyObject = DirectCast(_item.InputHitTest(p), DependencyObject)
        While obj Is Nothing = False AndAlso TypeOf obj Is childItem = False
            obj = VisualTreeHelper.GetParent(obj)
        End While
        Return DirectCast(obj, childItem)
    End Function
4

1 回答 1

0

我找到了这个解决方案(但我不太喜欢它)。问题取决于 wpf 由于某些原因不记得存在的添加项目。然后我使用清除并重新添加源集合中所有项目的方法进行“手动”刷新:

Public Sub RefreshData(ByVal RicambiListPass As ObservableCollection(Of P_RicambiItem))
    Dim l As New List(Of P_RicambiItem)
    l.AddRange(RicambiListPass)
    _RicambiList.Clear()
    For Each i As P_RicambiItem In l
        _RicambiList.Add(i)
    Next
End Sub
于 2010-07-14T15:50:18.790 回答