CodeCopy

September 16, 2009

Wpf UIElement keyboard focus helper

Filed under: c#,wpf — sterndorff @ 10:15
Tags: , ,

Ever had problems setting focus on a wfp control? I’ve found a small and ugly way to help. Using this extention method helps in a lot of scenarios:


public static class FocusHelper
{
    public static void DelayedFocus(this UIElement uiElement)
    {
        uiElement.Dispatcher.BeginInvoke(
        new Action(delegate
        {
            uiElement.Focusable = true;
            uiElement.Focus();
            Keyboard.Focus(uiElement);
        }),
        DispatcherPriority.Render);
    }
}

And yes I know it’s not pretty. Longer discussion here: http://apocryph.org/2006/09/10/wtf_is_wrong_with_wpf_focus/

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.