我有一个带有此控件的窗口。
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
///elemnts in row 0
<StackPanel Grid.Row="1">
<ToolBar x:Name="Toolbar">
<Label Content="TextPattern" />
<ComboBox></ComboBox>
<Button Command="{Binding ScanCommand}">
<Image Source="/Images/sacn.png"></Image>
</Button>
<Button Command="{Binding FaxCommand}" x:Name="FaxButton" PreviewKeyDown="FaxButton_PreviewKeyDown">
<Image Source="/Images/fax.png"></Image>
</Button>
</ToolBar>
<TextBox Width="{Binding ElementName=Toolbar,Path=ActualWidth}" x:Name="BodyTextBox" Focusable="True" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Body}"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="2" >
<Button Content="Save" Command="{Binding SaveCommand}"></Button>
<Button Content="Cancel" Command="{Binding CancelCommand}"></Button>
</StackPanel>
</Grid>
当我使用tab键获得焦点时,它会在按下传真按钮后转到保存按钮。但我想去BodyTextbox。
我使用PreviewKeyDown
进行设定焦点。
private void FaxButton_PreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key==Key.Tab)
{
BodyTextBox.Focus();
BodyTextBox.SelectAll();
FocusManager.SetFocusedElement(this, BodyTextBox);
}
}
但不要设置焦点。
答案 0 :(得分:0)
加载UserControl或Windowcontrol时: 请在UserCOntrol_Load事件中写下这个:
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
new Action(delegate ()
{
BodyTextBox.Focus(); // Set Logical Focus
Keyboard.Focus(BodyTextBox); // Set Keyboard Focus
}));
它会自动对焦n你也可以在没有按任何标签的情况下从键盘上写内容..
希望这对你有用..
谢谢, 普利文
答案 1 :(得分:0)
删除PreviewKeyDown事件并在工具栏中添加KeyboardNavigation.TabNavigation =“Continue”
<ToolBar x:Name="Toolbar" KeyboardNavigation.TabNavigation="Continue">