Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on a textbox control in UserControl in wpf

Tags:

wpf

I have created an UserControl which is loaded in a View (Window) in WPF. In my user control I have put a TextBox. I am unable to set focus on this text box when my view loads. I have tried following but nothing works for me:

  1. FocusManager.FocusedElement="{Binding ElementName=PwdBox}"

  2. I have created a FocusExtension to set focus on control.

Please help.

like image 590
Palak.Maheria Avatar asked Oct 07 '13 12:10

Palak.Maheria


1 Answers

Another option that you have is to create a bool IsFocusedproperty in your view model. Then you can add a DataTrigger to set the focus when this property is true:

In a Resources section:

<Style x:Key="SelectedTextBoxStyle" TargetType="{x:Type TextBox}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsFocused}" Value="True">
            <Setter Property="FocusManager.FocusedElement" 
                Value="{Binding RelativeSource={RelativeSource Self}}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

...

<TextBox Style="{StaticResource SelectedTextBoxStyle}" ... />

Note that at times, you may need to set it to false first to get it to focus (only when it is already true):

IsFocused = false;
IsFocused = true;
like image 60
Sheridan Avatar answered Oct 26 '22 08:10

Sheridan