Focus Textbox using FocusManager.FocusedElement issue

跟風遠走 提交于 2019-12-07 12:15:59

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/17980224/focus-textbox-using-focusmanager-focusedelement-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!