private static void PropertyToSetFocusPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as SetFocusFromPropertyBehavior; if (control != null && e.NewValue != null) { var nameToFind = string.Empty; if (!string.IsNullOrEmpty(control.ParentPropertyToSetFocus)) { nameToFind = control.ParentPropertyToSetFocus + "_" + e.NewValue.ToString(); } else { nameToFind = e.NewValue.ToString(); } var controlToSetFocus = control.AssociatedObject.FindName(nameToFind); if (controlToSetFocus != null) { var c = controlToSetFocus as Control; if (c != null) { AutoGenerateForm.Uwp.AutoGenerator generator = null; if (control.AssociatedObject is AutoGenerateForm.Uwp.AutoGenerator) { generator = (AutoGenerateForm.Uwp.AutoGenerator)control.AssociatedObject; } else { generator = control.AssociatedObject.GetFirstDescendantOfType <AutoGenerateForm.Uwp.AutoGenerator>(); } c.Focus(FocusState.Pointer); if (generator == null) { Debug.WriteLine(" auto generator not found"); return; } else { control.SetViewForItem(c, generator); } } } } }
internal async Task SetViewForItem(FrameworkElement item, AutoGenerateForm.Uwp.AutoGenerator generator) { var listView = generator.GetFirstDescendantOfType <ListView>(); var scrollViewer = listView.GetFirstDescendantOfType <ScrollViewer>(); if (scrollViewer == null) { Debug.WriteLine(" scrollviewer not found"); return; } var field = item.GetAncestorsOfType <Controls.FieldContainerControl>().FirstOrDefault(); ListViewItem listViewItem = null; listViewItem = listView.ContainerFromItem(field) as ListViewItem; // Calculations relative to screen or ListView if (listViewItem == null) { Debug.WriteLine(" child element not found"); return; } var topLeft = listViewItem .TransformToVisual(generator) .TransformPoint(new Point()).Y; var lvih = listViewItem.ActualHeight; var lvh = generator.ActualHeight; var desiredTopLeft = (lvh - lvih) / 2.0; var desiredDelta = topLeft - desiredTopLeft; // Calculations relative to the ScrollViewer within the ListView var currentOffset = scrollViewer.VerticalOffset; var desiredOffset = currentOffset + desiredDelta; scrollViewer.ChangeView(null, desiredOffset, null); }