Search code examples
wpftextboxfocusmanager

Focus Textbox using FocusManager.FocusedElement issue


I'm trying to set the keyboard focus to a textbox that is included in a stackpanel. When the IsEditMode becomes true i want the textbox to become, by default, focused.

I've tried this code:

<DataTemplate x:Key="LibraryItemTemplate">
<StackPanel Orientation="Vertical">
    <StackPanel.Style>
       <Style TargetType="StackPanel">
          <Style.Triggers>
               <DataTrigger Binding="{Binding IsEditMode}" Value="True">
                   <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=TxtB}"/>
               </DataTrigger>
          </Style.Triggers>
       </Style>
    </StackPanel.Style>

    <TextBlock x:Name="TxtA" Text="A" />
    <TextBox x:Name="TxtB" Text="B" Visibility="{Binding IsEditMode, Converter={StaticResource BoolVisibilityCollapsed}}"/>
</StackPanel>
</DataTemplate>
....
<ListView x:Name="LibraryListView" SelectedItem="{Binding SelectedItem,   UpdateSourceTrigger=PropertyChanged}" >
<ListView.View>
    <GridView>
        <GridViewColumn CellTemplate="{StaticResource LibraryItemTemplate}"  Width="Auto"/>
    </GridView>
</ListView.View>

But the problem is the mouse doesn't marking seems the keyboard focus is not in textbox and I have to click by mouse once again to TextBox to be able to input some text in TextBox.

Any idea?


Solution

  • After FocusManager is setting the focus you have to handle this event and in the event you have to add

    <TextBox x:Name="TxtB" 
             Text="B" 
             GotFocus="TxtB_GotFocus"  
             Visibility="{Binding IsEditMode
                 , Converter={StaticResource BoolVisibilityCollapsed}}"/>
    
    ....
    private void TxtB_GotFocus(object sender, RoutedEventArgs e)
    {
        this.Dispatcher.BeginInvoke((Action)delegate
        {
           Keyboard.Focus(TxtB);
        }, DispatcherPriority.Render);
    }
    

    Thanks a lot to Darlene

    And I'm adding the answer by myself to meet Sheridan's suggestion Thanks a lot