欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF TreeView SelectedItemChanged called twice

程序员文章站 2022-05-03 13:53:28
How to avoid WPF TreeView SelectedItemChanged being called twice Very often, we need to execute some code in SelectedItemChanged depending on the sele ......

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)
{
  dispatcher.begininvoke(dispatcherpriority.background, 
        (noargdelegate)delegate { myfunction(); });
}