Skip to content

Instantly share code, notes, and snippets.

@tswann
Created March 29, 2011 10:57
Show Gist options
  • Save tswann/892163 to your computer and use it in GitHub Desktop.
Save tswann/892163 to your computer and use it in GitHub Desktop.
WPF FocusBehaviour
using System;
using System.Windows;
namespace MyProject.WPF.Helpers
{
/// <summary>
/// Allows an arbitrary UI element to bind keyboard focus to an attached property.
/// </summary>
public static class FocusBehaviour
{
public static bool GetHasKeyboardFocus(DependencyObject obj)
{
return (bool)obj.GetValue(HasKeyboardFocusProperty);
}
public static void SetHasKeyboardFocus(DependencyObject obj, bool value)
{
obj.SetValue(HasKeyboardFocusProperty, value);
}
// Using a DependencyProperty as the backing store for HasKeyboardFocus. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HasKeyboardFocusProperty =
DependencyProperty.RegisterAttached("HasKeyboardFocus",
typeof(bool),
typeof(FocusBehaviour),
new UIPropertyMetadata(false, null, CoerceCurrentValue));
/// <summary>
/// Coerce property value and give focus to bound control if true.
/// </summary>
/// <param name="source">UIElement to which this property has been attached.</param>
/// <param name="value">Property value</param>
/// <returns>Property value</returns>
private static object CoerceCurrentValue(DependencyObject source, object value)
{
UIElement control = source as UIElement;
if (control != null)
{
bool hasFocus = (bool)value;
if (hasFocus)
{
System.Threading.ThreadPool.QueueUserWorkItem((a) =>
{
control.Dispatcher.Invoke(new Action(() =>
{
control.Focus();
}));
});
}
}
return value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment