WPF: Can't get my control to take focus

myermian picture myermian · Apr 1, 2011 · Viewed 8.4k times · Source

I can't seem to get my control to actually take the focus:

XAML:

<Button Command={Binding SetGridToVisibleCommand} />
<Grid Visibility="{Binding IsGridVisible, Converter={con:VisibilityBooleanConverter}}">
    <TextBox Text={Binding MyText} IsVisibleChanged="TextBox_IsVisibleChanged" />
</Grid>

XAML.cs:

private void TextBox_IsVisibleChanged(Object sender, DependencyPropertyChangedEventArgs e)
{
    UIElement element = sender as UIElement;

    if (element != null)
    {
        Boolean success = element.Focus(); //Always returns false and doesn't take focus.
    }
}


The ViewModel does it's job of setting the IsGridVisible to true, and the converter does it's job by converting that value to Visibility.Visible (I snooped it).

Answer

H.B. picture H.B. · Apr 1, 2011

Not all UIElements can be focused by default, have you tried setting Focusable to true before trying Focus()?