开发者

Setting Keyboard Focus on Child Control in TabItem that Is Not Selected

开发者 https://www.devze.com 2023-04-12 08:35 出处:网络
I looked through several questions (both in and out of stackoverflow.com) and could not find one that answers my question. If you\'re aware of one, please let me know.

I looked through several questions (both in and out of stackoverflow.com) and could not find one that answers my question. If you're aware of one, please let me know.

The scenario is this: I would like to set a control to have keyboard focus when the control is in a TabItem that is not selected.

Sample XAML:

<Window x:Class="WPF_Application1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        >
    <Grid>
        <TabControl>
            <TabItem Name="tab1" Header="tab1">
                     <Button Name="button" Content="set focus" Height="24" W开发者_运维知识库idth="57" Click="button_Click" />
                </TabItem>
            <TabItem Name="tab2" Header="tab2">
                <TextBox Name="text" Height="23" Width="331" />
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Sample XAML code-behind:

namespace WPF_Application1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()           
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            Keyboard.Focus(text); // doesn't work
            text.Focus(); // doesn't work
        }

    }
}

Any suggestions?


I found a solution here. It seems like the TabItem(s) must be selected, the Window.UpdateLayout() method must be called, then the focus is set on the control. We may just create an extension method to handle this for UIElements behind-the-scene, since this type of behavior is how we would want the normal Focus to work...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号