Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autocompletebox focus in wpf

when I try to focus on my "autocompletetextbox" I failed I write autocompletetextbox.focus() but the cursor still focus in another what should I do or write to enable to write in it or focus?

like image 577
kartal Avatar asked Aug 26 '10 05:08

kartal


5 Answers

I experienced the same thing -- it does not work properly in its current form (I expect you're talking about the AutoCompleteBox that comes with the February 2010 release of WPFToolkit).

I created a subclass:

public class AutoCompleteFocusableBox : AutoCompleteBox
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        var textbox = Template.FindName("Text", this) as TextBox;
        if(textbox != null) textbox.Focus();
    }
}

This sets focus to the actual TextBox (called "Text") that is part of the default ControlTemplate.

like image 192
Jay Avatar answered Sep 22 '22 10:09

Jay


You will have to override the Focus method to find the template of the Textbox.

public class FocusableAutoCompleteBox : AutoCompleteBox
{
    public new void Focus()
    {
        var textbox = Template.FindName("Text", this) as TextBox;
        if (textbox != null) textbox.Focus();
    }
}
like image 31
Pascalsz Avatar answered Sep 24 '22 10:09

Pascalsz


This is very old question, but I want to share my work-around.

Keyboard.Focus(autocompletetextbox);
autocompletetextbox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

This works in WPFToolkit v3.5.50211.1 on Visual Studio Express 2015 for Windows Desktop

like image 38
noobar Avatar answered Sep 23 '22 10:09

noobar


It seems that you have to wait for the auto complete box to load first. Then set focus

<sdk:AutoCompleteBox 
   x:Name="_employeesAutoCompleteBox" 
   ItemsSource="{Binding Path=Employees}" 
   SelectedItem="{Binding SelectedEmployee, Mode=TwoWay}" 
   ValueMemberPath="DisplayName" >    
</sdk:AutoCompleteBox>
_employeesAutoCompleteBox.Loaded +=
    (sender, e) => ((AutoCompleteBox)sender).Focus();
like image 24
user1035988 Avatar answered Sep 23 '22 10:09

user1035988


This is my solution,

I found it easier than having inherited class

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    var textBox = FindVisualChild<TextBox>(CodedCommentBox);
    textBox.Focus();
}

private TChildItem FindVisualChild<TChildItem>(DependencyObject obj) where TChildItem : DependencyObject
{
    for (var i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
    {
        var child = VisualTreeHelper.GetChild(obj, i);

        var item = child as TChildItem;
        if (item != null)
        {
            return item;
        }

        var childOfChild = FindVisualChild<TChildItem>(child);
        if (childOfChild != null)
        {
            return childOfChild;
        }
    }

    return null;
}
like image 43
Mohini Mhetre Avatar answered Sep 25 '22 10:09

Mohini Mhetre