Click here to Skip to main content
12,753,418 members (35,433 online)
Click here to Skip to main content

Stats

100.1K views
3K downloads
40 bookmarked
Posted 26 Jul 2009

Using the WPF FocusScope

, 26 Jul 2009 MIT
Explains why WPF seems to break if you try to use FocusScope, and provides a simple solution.
/*
 * Created by SharpDevelop.
 * User: Daniel
 * Date: 26.07.2009
 * Time: 17:56
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace TestApp
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
		public Window1()
		{
			InitializeComponent();
		}
		
		void Box1_MouseDown(object sender, MouseButtonEventArgs e)
		{
			// How should we know what was last active in the group box?
			object keyboardNavigation = typeof(KeyboardNavigation).InvokeMember(
				"Current",
				BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.GetProperty,
				null, null, null);
			object activeElement = typeof(KeyboardNavigation).InvokeMember(
				"GetActiveElement",
				BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
				null,
				keyboardNavigation,
				new object[] { box1 });
			IInputElement focusedElement = activeElement as IInputElement;
			if (focusedElement != null) {
				Keyboard.Focus(focusedElement);
			} else {
				box1.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
			}
		}
		
		void Box2_MouseDown(object sender, MouseButtonEventArgs e)
		{
			IInputElement focusedElement = FocusManager.GetFocusedElement(box2);
			if (focusedElement != null) {
				Keyboard.Focus(focusedElement);
			} else {
				box2.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
			}
		}
		
		void Box3_MouseDown(object sender, MouseButtonEventArgs e)
		{
			EnhancedFocusScope.SetFocusOnActiveElementInScope(box3);
		}
	}
}

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

Share

About the Author

Daniel Grunwald
Germany Germany
I am the lead developer on the SharpDevelop open source project.

You may also be interested in...

Pro
Pro
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170217.1 | Last Updated 27 Jul 2009
Article Copyright 2009 by Daniel Grunwald
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid