Click here to Skip to main content
15,936,709 members
Articles / Desktop Programming / WPF

WPF TreeView SelectedItemChanged called twice

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
9 Jun 2011CPOL 38.7K   3   5
How to avoid WPF TreeView SelectedItemChanged being called twice

Very often, we need to execute some code in SelectedItemChanged depending on the selected TreeViewItem. But SelectedItemChanged 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 in SelectedItemChanged. 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)
        (NoArgDelegate)delegate { MyFunction(); });


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) Al Kaffary
Saudi Arabia Saudi Arabia
I am Computer Science graduate and working in Microsoft technologies (VB.Net/C#, ASP.Net, WPF, WCF, SQL Server 2005/2008, Web Services).

Comments and Discussions

QuestionIt's working Pin
Member 139372026-Aug-19 0:28
Member 139372026-Aug-19 0:28 
GeneralYes, it's an anonymous method. Assuming "MyFunction" doesn'... Pin
Richard Deeming14-Jun-11 7:14
mveRichard Deeming14-Jun-11 7:14 
GeneralI think this is an anonymous method, but I'm not entirely su... Pin
KenBonny13-Jun-11 20:04
KenBonny13-Jun-11 20:04 
GeneralTruly speaking I do not know the exact name but this syntax ... Pin
Kanwal Shehzad12-Jun-11 1:37
professionalKanwal Shehzad12-Jun-11 1:37 
Generalwhat does this means here...there is no "()" after "delegate... Pin
Pritesh Aryan10-Jun-11 23:49
Pritesh Aryan10-Jun-11 23:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.