4

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?

artos
  • 751
  • 1
  • 10
  • 25
  • Do you still have this issue if TxtB is always visible? (Remove the visbility binding for now.) I'm wondering if TxtB is not yet visible when you're trying to focus it. Also have you seen this SO post? http://stackoverflow.com/questions/3109080/focus-on-textbox-when-usercontrol-change-visibility – Darlene Jul 31 '13 at 20:35
  • Ok I remove visibility and it works, but still I need to hide it somehow and show TextBlock if IsEditMode is false and the opposite. So how to implement this functionality? – artos Jul 31 '13 at 20:55
  • Look at this StackOverflow post that discusses focusing a textbox when it becomes visible. http://stackoverflow.com/questions/3109080/focus-on-textbox-when-usercontrol-change-visibility – Darlene Jul 31 '13 at 21:07
  • I've tried that one also and it works also so we have 2 way to implement this, thanks a lot – artos Jul 31 '13 at 21:13
  • If this is solved, how about adding an answer someone? – Sheridan Aug 01 '13 at 08:43

1 Answers1

3

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

JiBéDoublevé
  • 4,124
  • 4
  • 36
  • 57
artos
  • 751
  • 1
  • 10
  • 25