2

我在 WPF 中有一个 tabcontrol 当我切换到特定的 tabItem 时,我想将焦点设置在特定的 textBox 上

我添加了 textBox_n.Focus(); 的代码 在 selectionChanged 的​​事件处理程序中,但它不起作用。

我在 tabItem 的 GotFocus 的事件处理程序中添加了代码,但很有趣的是,调用 textBox_n.Focus() 时再次调用了 tabItem 的 GotFocus。

所以在哪里和什么地方放它的最佳位置。

4

1 回答 1

0

如果您使用网格来排列文本框,您可以将要关注的网格作为网格的第一个子项,并将其行和列指定为第二个或第三个,这是一个示例。

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

当然不是很优雅,但它可以快速完成工作。也不需要代码隐藏。

于 2009-08-13T19:47:33.877 回答