使用 FocusManager.FocusedElement 问题的焦点文本框 [英] Focus Textbox using FocusManager.FocusedElement issue

查看:19
本文介绍了使用 FocusManager.FocusedElement 问题的焦点文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将键盘焦点设置为包含在堆栈面板中的文本框.当 IsEditMode 变为 true 时,我希望文本框默认成为焦点.

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.

我试过这个代码:

<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.

有什么想法吗?

推荐答案

FocusManager 设置焦点后,您必须处理此事件,并且必须添加事件

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);
}

非常感谢达琳

我自己添加答案以满足谢里丹的建议非常感谢

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

这篇关于使用 FocusManager.FocusedElement 问题的焦点文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆