serialhobbyist
serialhobbyist

Reputation: 4815

How do I give the focus to a TextBox in a DataForm?

I've got a small DataForm and I want to set the focus on the first TextBox. I'm using the Novermber 2009 Toolkit. I've named the TextBox and tried using .Focus() from the DataForm's loaded event. I see it get focus for one cursor 'blink' and then it's gone. I'm trying to work out if this is an artefact of the DataForm or something else. Does anyone know if I should be able to do this?

Upvotes: 4

Views: 1933

Answers (3)

Myles J
Myles J

Reputation: 2880

I tried loads of suggestions e.g. using Dispatcher, UpdateLayout etc etc. floating around on various internet sites and none of them worked reliably for me. In the end I settled on the following:

private bool _firstTime = true;

    private void MyChildWindow_GotFocus(object sender, RoutedEventArgs e)
    {
        if (_firstTime)
        {
            try
            {
                var dataForm = MyDataForm;
                var defaultFocus = dataForm.FindNameInContent("Description") as TextBox;
                defaultFocus.Focus();
            }
            catch (Exception)
            {
            }
            finally
            {
                _firstTime = false;
            }
        }
    }

Not pretty I know...but it works. There appears to be a timing issue with using the Focus() method in SL4.

Upvotes: 1

witters
witters

Reputation: 751

A little trick I've used successfully is to subscribe to the Loaded event of the textbox, then in the event handler, I set the focus with code such as this:

private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
            TextBox usernameBox = (TextBox)sender;
            Dispatcher.BeginInvoke(() => { usernameBox.Focus(); });
}

Upvotes: 1

Jim McCurdy
Jim McCurdy

Reputation: 2052

Try calling my custom focus setting function (FocusEx).

internal static class ControlExt 
{ 
    // Extension for Control 
    internal static bool FocusEx(this Control control) 
    { 
        if (control == null) 
                return false; 

        bool success = false; 
        if (control == FocusManager.GetFocusedElement()) 
                success = true; 
        else 
        { 
                // To get Focus() to work properly, call UpdateLayout() immediately before 
                control.UpdateLayout(); 
                success = control.Focus(); 
        } 

        ListBox listBox = control as ListBox; 
        if (listBox != null) 
        { 
                if (listBox.SelectedIndex < 0 && listBox.Items.Count > 0) 
                        listBox.SelectedIndex = 0; 
        } 

        return success; 
    } 
} 

That should work for you.

Jim McCurdy

YinYangMoney

Upvotes: 0

Related Questions