Click here to Skip to main content
15,886,110 members
Articles / Desktop Programming / WPF

Using the WPF FocusScope

Rate me:
Please Sign up or sign in to vote.
4.97/5 (22 votes)
26 Jul 2009MIT5 min read 154.6K   3.8K   46  
Explains why WPF seems to break if you try to use FocusScope, and provides a simple solution.
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace TestApp
{
	/// <summary>
	/// Attached behavior for improved focus scope handling.
	/// </summary>
	public static class EnhancedFocusScope
	{
		public static void SetFocusOnActiveElementInScope(UIElement scope)
		{
			IInputElement focusedElement = FocusManager.GetFocusedElement(scope);
			if (focusedElement != null) {
				Keyboard.Focus(focusedElement);
			} else {
				scope.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
			}
		}
		
		public static bool GetIsEnhancedFocusScope(UIElement element)
		{
			return (bool)element.GetValue(IsEnhancedFocusScopeProperty);
		}
		
		public static void SetIsEnhancedFocusScope(UIElement element, bool value)
		{
			element.SetValue(IsEnhancedFocusScopeProperty, value);
		}
		
		public static readonly DependencyProperty IsEnhancedFocusScopeProperty =
			DependencyProperty.RegisterAttached(
				"IsEnhancedFocusScope",
				typeof(bool),
				typeof(EnhancedFocusScope),
				new UIPropertyMetadata(false, OnIsEnhancedFocusScopeChanged));
		
		static void OnIsEnhancedFocusScopeChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
		{
			UIElement item = depObj as UIElement;
			if (item == null)
				return;
			
			if ((bool)e.NewValue) {
				FocusManager.SetIsFocusScope(item, true);
				item.GotKeyboardFocus += OnGotKeyboardFocus;
			} else {
				FocusManager.SetIsFocusScope(item, false);
				item.GotKeyboardFocus -= OnGotKeyboardFocus;
			}
		}
		
		static void OnGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
		{
			IInputElement focusedElement = e.NewFocus;
			for (DependencyObject d = focusedElement as DependencyObject; d != null; d = VisualTreeHelper.GetParent(d)) {
				if (FocusManager.GetIsFocusScope(d)) {
					d.SetValue(FocusManager.FocusedElementProperty, focusedElement);
					if (!(bool)d.GetValue(IsEnhancedFocusScopeProperty)) {
						break;
					}
				}
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Germany Germany
I am the lead developer on the SharpDevelop open source project.

Comments and Discussions