internal async Task<bool> SelectItem(UIElement element, bool refreshOnFail = false) { var ancestors = new[] { element }.Concat(element.GetAncestors()).ToList(); if (this.RootElements == null || this.RootElements.Count == 0) { await Refresh(); } var vm = this.RootElements[0] as DependencyObjectViewModel; var ancestorIndex = ancestors.IndexOf(vm.Model); if (ancestorIndex < 0) { for (int i = 1; i < this.RootElements.Count && ancestorIndex < 0; i++) { // Handling popups var popup = this.RootElements[i]; if (!popup.IsExpanded) { await popup.LoadChildrenAsync(); popup.IsExpanded = true; } if (popup.Children.Count > 0) { vm = popup.Children[0] as DependencyObjectViewModel; ancestorIndex = ancestors.IndexOf(vm.Model); } } if (ancestorIndex < 0) { await Refresh(); ancestorIndex = ancestors.IndexOf(vm.Model); } } if (ancestorIndex < 0) { System.Diagnostics.Debug.WriteLine("Something's wrong, but let's not throw exceptions here."); //Debugger.Break(); if (refreshOnFail) { await Refresh(); return await SelectItem(element, false); } return false; } //Debug.Assert(vm.Model == ancestors[0]); for (ancestorIndex = ancestorIndex - 1; ancestorIndex >= 0; ancestorIndex--) { if (!vm.IsExpanded) { await vm.LoadChildrenAsync(); vm.IsExpanded = true; } var child = vm.Children.OfType<DependencyObjectViewModel>() .FirstOrDefault(dovm => dovm.Model == ancestors[ancestorIndex]); if (child == null) { System.Diagnostics.Debug.WriteLine("Something's wrong, but let's not throw exceptions here."); //Debugger.Break(); if (refreshOnFail) { vm.Children.Clear(); //await vm.LoadPropertiesAsync(); await vm.LoadChildrenAsync(); //if (vm.Parent == null) //{ // await Refresh(); //} //else //{ // // do a partial refresh on the stale subtree // var i = vm.Parent.Children.IndexOf(vm); // vm.Parent.Children.RemoveAt(i); // vm.Parent.Children.Insert(i, new DependencyObjectViewModel(this, vm.Parent, ancestors[ancestorIndex])); //} return await SelectItem(element, false); } return false; } vm = child; } await Task.Delay(100); vm.IsSelected = true; return true; }