【问题标题】:how to set focus to a textbox如何将焦点设置到文本框
【发布时间】:2016-01-19 05:38:30
【问题描述】:

我有一个带有这个控件的窗口。

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

当我使用制表键获取焦点时,按下传真按钮的制表符后会转到保存按钮。但我想去 BodyTextbox。

我使用PreviewKeyDown 设置焦点。

 private void FaxButton_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key==Key.Tab)
        {
            BodyTextBox.Focus();
            BodyTextBox.SelectAll();
            FocusManager.SetFocusedElement(this, BodyTextBox);
        }
    }

但不要设置焦点。

【问题讨论】:

    标签: wpf focus


    【解决方案1】:

    当您加载 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 你也可以在不按任何标签的情况下从键盘写入内容..

    希望这对美国有用..

    谢谢, 普拉文

    【讨论】:

    • 谢谢,但我想在按传真按钮时获得焦点。
    • KeyboardNavigation.TabIndex="0"
    • 将此添加到您的文本框控件
    【解决方案2】:

    移除 PreviewKeyDown 事件并在工具栏中添加 KeyboardNavigation.TabNavigation="Continue"

     <ToolBar x:Name="Toolbar" KeyboardNavigation.TabNavigation="Continue">
    

    【讨论】:

    • 谢谢,但是当我使用此代码时,它会转到文本框,但不要转到工具栏中的元素。
    • 是的,它指向工具栏中的所有元素。请清楚地解释您的问题。
    • 我在工具栏之前有多个控件,使用Tab 在控件之间移动。在工具栏的最后一个控件中,当按 tab 时,转到保存按钮而不是转到 BodyTextBox。
    猜你喜欢
    • 2014-04-24
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多