2010-06-07 82 views
0

我有一個TreeView WPF和2級數據。
我已經從TreeViewItemTemplate中刪除了ToogleButton。現在,我想通過單擊鼠標單擊來展開/摺疊組(而不是雙擊作爲默認行爲)。
我已經試過這樣:在第一次點擊後再次選擇WPF TreeviewITem

Private Sub tvArt_SelectedItemChanged(ByVal sender As System.Object, _ 
    ByVal e As RoutedPropertyChangedEventArgs(Of System.Object)) Handles tvArt.SelectedItemChanged 

    If e.NewValue Is Nothing = False Then 
     Dim ri As P_RicambiItem = TryCast(e.NewValue, P_RicambiItem) 
     If ri Is Nothing = False Then 
      If ri.isExpanded Then 
       ri.isExpanded = False 
      Else 
       ri.isExpanded = True 
      End If 
      ri.isSelected = False 
     End If 
    End If 
End Sub 

在收集數據源使用我的財產isExpandedisSelected

但是它只工作一半:第一次點擊後,事實上,我不能再次點擊同一項目,因爲即使我已經取消選擇它,事件處理程序「記得」它是最後選擇的項目,它不捕獲事件SelectedItemChanged

我該怎麼辦?

回答

2

最簡單的方法可能是處理上的TreeView的PreviewMouseDown事件,並確定當鼠標點擊父TreeViewItems:

XAML:

<TreeView Name="treeView1" TreeView.PreviewMouseDown="OnTreeViewPreviewMouseDown" /> 

代碼隱藏:

private void OnTreeViewPreviewMouseDown(object sender, MouseButtonEventArgs e) 
{ 
    TreeViewItem tvi = GetTreeViewItemClicked((FrameworkElement) e.OriginalSource, treeView1); 
    if (null == tvi) return; 
    tvi.IsExpanded = !tvi.IsExpanded; 
} 

private static TreeViewItem GetTreeViewItemClicked(UIElement sender, UIElement treeView) 
{ 
    Point p = sender.TranslatePoint(new Point(0, 0), treeView); 
    var obj = treeView.InputHitTest(p) as DependencyObject; 
    while (obj != null && !(obj is TreeViewItem)) 
    { 
     obj = VisualTreeHelper.GetParent(obj); 
    } 
    return obj as TreeViewItem; 
} 
+0

謝謝!但是我找不到TreeView的「Click」事件。在「MouseUp」事件中,我看不到數據,因爲treeviewitem仍未選中。你可以給我看一小段代碼嗎? C#很好,我會做「翻譯」。 – lamarmora 2010-06-07 07:53:37

+0

對,對不起。這有點誤導。我更新了處理PreviewMouseDown事件的方法。 – hemp 2010-06-07 08:03:22

+0

非常感謝!它運作良好! – lamarmora 2010-06-07 09:11:11

1

非常感謝你!它工作得很好,如果有人應該有興趣,這是我的Vb版本:

Private Sub tvArt_PreviewMouseDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs) Handles tvArt.PreviewMouseDown 
    Dim tvi As TreeViewItem = GetTreeViewItemClicked(e.OriginalSource, Me.tvArt) 
    If tvi Is Nothing = False Then 
     If tvi.HasItems Then 
      tvi.isExpanded = Not tvi.isExpanded 
     End If 
    End If 
End Sub 

Private Function GetTreeViewItemClicked(ByVal sender As UIElement, ByVal _treeView As UIElement) As TreeViewItem 
    Dim p As Point = sender.TranslatePoint(New Point(0, 0), _treeView) 
    Dim obj As DependencyObject = DirectCast(_treeView.InputHitTest(p), DependencyObject) 
    While obj Is Nothing = False AndAlso TypeOf obj Is TreeViewItem = False 
     obj = VisualTreeHelper.GetParent(obj) 
    End While 
    Return DirectCast(obj, TreeViewItem) 
End Function 
相關問題