wpf 使用 FocusManager.FocusedElement 问题的焦点文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17980224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Focus Textbox using FocusManager.FocusedElement issue
提问by artos
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.
我正在尝试将键盘焦点设置为包含在堆栈面板中的文本框。当 IsEditMode 变为 true 时,我希望文本框默认成为焦点。
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?
任何的想法?
采纳答案by artos
After FocusManager is setting the focus you have to handle this event and in the event you have to add
在 FocusManager 设置焦点后,您必须处理此事件,并且在必须添加的事件中
<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
我自己添加答案以满足谢里丹的建议 非常感谢

