1.TreeView選擇事件執行兩次
Very often, we need to execute some code in SelectedItemChanged
depending on the selected TreeViewItem
. ButSelectedItemChanged
is called twice. This is due to stealing focus from the main window, which is screwing something up.
What we have to do to avoid this is simply delay the call to our code, i.e., MyFunction()
which we need to execute inSelectedItemChanged
. Here's a workaround which delays the call to open the new window until the item selection code finishes up:
private delegate void NoArgDelegate(); void Window1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { Dispatcher.BeginInvoke(DispatcherPriority.Background, (NoArgDelegate)delegate { MyFunction(); }); }
2.Treeview獲取父節點
private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { //節點(是子節點或者是根節點) TreeViewItem item = treeView1.SelectedItem as TreeViewItem; //獲取父節點 TreeViewItem parent = item.Parent as TreeViewItem; //判斷父節點是否存在 if (parent != null) { //顯示父節點信息,這里顯示 Header 信息 MessageBox.Show("父節點的Header:" + parent.Header.ToString()); } else { MessageBox.Show("沒有父節點!"); } }