简体   繁体   English

TabControl并将焦点设置在WPF中的文本框上

[英]TabControl and set the focus on a textbox in WPF

I have a tabcontrol in WPF When I switch to a specific tabItem , I want to set the focus on a specific textBox 我在WPF中有一个tabcontrol当我切换到特定的tabItem时,我想将焦点设置在特定的textBox上

I added the code of textBox_n.Focus(); 我添加了textBox_n.Focus()的代码; in the event handler of selectionChanged, but it didn't work. 在selectionChanged的事件处理程序中,但是它不起作用。

I added the code in the event handler of the tabItem's GotFocus, but funny enough calling textBox_n.Focus(), was calling the tabItem's GotFocus again. 我在tabItem的GotFocus的事件处理程序中添加了代码,但有趣的是调用textBox_n.Focus(),再次调用了tabItem的GotFocus。

so where and what the best place to put it. 所以放在哪里和什么地方最好。

If you're using a grid to arrange the textboxes, you could put the grid you want to focus as the first child of the grid, and specify it's row and column to be the second or third, here's an example. 如果使用网格来排列文本框,则可以将要关注的网格作为网格的第一个子元素,并将其行和列指定为第二个或第三个,这是一个示例。

    <TabControl>
        <TabItem Header="Tab 1">

        </TabItem>
        <TabItem Header="Tab 2">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <TextBox Grid.Row="1" Margin="5">textBox2</TextBox> <!-- This textbox is the first child of the grid, so it gets focused -->
                <TextBox Grid.Row="0" Margin="5">textBox1</TextBox> <!-- This textbox is catually on top of textBox2 -->
            </Grid>
        </TabItem>
    </TabControl>

Not very elegant of course, but it gets the job done fast. 当然不是很优雅,但是可以很快完成工作。 Also no code-behind required. 也不需要任何代码隐藏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM