Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ForwardFocusBehavior
- : System.Windows.Interactivity.Behavior<FrameworkElement>
- {
- private FrameworkElement ForwardTo = null;
- protected override void OnAttached()
- {
- base.OnAttached();
- this.ForwardTo = (FrameworkElement)Find(
- AssociatedObject,
- d => d.GetType() == ForwardToChildOfType);
- this.ForwardFrom.GotKeyboardFocus += AssociatedObject_GotKeyboardFocus;
- }
- protected override void OnDetaching()
- {
- base.OnDetaching();
- this.ForwardFrom.GotKeyboardFocus -= AssociatedObject_GotKeyboardFocus;
- this.ForwardTo = null;
- }
- void AssociatedObject_GotKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e)
- {
- if (null == ForwardTo)
- {
- this.ForwardTo = (FrameworkElement)Find(
- AssociatedObject,
- d => d.GetType() == ForwardToChildOfType);
- }
- // Detect a reverse traversal request.
- if (e.OldFocus == ForwardTo
- && e.NewFocus == ForwardFrom
- && e.KeyboardDevice.IsKeyDown(Key.Tab))
- {
- this.ForwardFrom.MoveFocus(
- new TraversalRequest(FocusNavigationDirection.Previous));
- }
- else if (this.ForwardFrom.IsKeyboardFocused)
- {
- this.ForwardTo.Focus();
- }
- }
- public FrameworkElement ForwardFrom
- {
- get { return (FrameworkElement)GetValue(ForwardFromProperty); }
- set { SetValue(ForwardFromProperty, value); }
- }
- public static readonly DependencyProperty ForwardFromProperty =
- DependencyProperty.Register("ForwardFrom", typeof(FrameworkElement),
- typeof(ForwardFocusBehavior), new UIPropertyMetadata(null));
- public Type ForwardToChildOfType
- {
- get { return (Type)GetValue(ForwardToChildOfTypeProperty); }
- set { SetValue(ForwardToChildOfTypeProperty, value); }
- }
- public static readonly DependencyProperty ForwardToChildOfTypeProperty =
- DependencyProperty.Register("ForwardToChildOfType", typeof(Type),
- typeof(ForwardFocusBehavior), new UIPropertyMetadata(null));
- /// <summary>
- /// Searches for a child element of a DependencyObject that
- /// matches the lambda condition given.
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="name"></param>
- private static DependencyObject Find(DependencyObject obj, Func<DependencyObject, bool> condition)
- {
- if ((obj == null))
- return null;
- if (condition(obj))
- return obj;
- DependencyObject result = null;
- for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
- {
- result = Find(VisualTreeHelper.GetChild(obj, i), condition);
- if (null != result)
- return result;
- }
- return null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement