我在WPF应用程序(Framework 3.5 SP1)中的TreeView中遇到问题。 这是一个具有2级数据的TreeVIew。我以特定的方式展开/折叠第一层的项目(只需单击鼠标并单击TreeViewItem)。当我展开一级TreeViewItem时,我向该组添加了一些二级TreeViewItems(这是一个重要的细节,事实上,如果我不添加项目,问题不会发生)。所有的作品都很好,直到TreeView失去焦点。 例如,如果我在第一个位置展开TreeViewItem,同时添加一个元素到第二个级别,然后点击一个按钮(让TreeView失去焦点),然后再次单击TreeViewItem放在第三个位置来扩展它,TreeViewItem不是“真正的”TreeViewItem(在这种情况下是第三个),而是一个TreeViewItem,它位于比第一个位置更高的位置点击(在这里是第二个)。 我试图在TreeView-LostFocus事件上使用UpdateLayout方法,但没有结果。可能我需要一个相反的方法:从UI开始,刷新包含TreeViewItems位置的对象。 你能帮我吗? 谢谢! Pileggi当它失去焦点时,WPF刷新TreeView
这是代码:
' 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