如何将光标焦点放在文本框上?

时间:2016-04-25 09:52:31

标签: c# wpf user-controls focus

我有一个WPF用户控件,其中包含控件,我想将焦点放在我试图使用“FocusManager.FocusedElement”的文本框上,但我无法输入bacause选项卡设置为usercontrol中的第一个控件。

enter image description here

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="10"/>
            <RowDefinition Height="45"/>
            <RowDefinition Height="160"/>
            <RowDefinition Height="50"/>
            <RowDefinition Height="15"/>
            <RowDefinition Height="272*"/>
        </Grid.RowDefinitions>

        <Button Grid.Row="1" x:Name="btnCreationOffre" Background="Transparent" Width ="120" Height="35" BorderBrush="{x:Null}" HorizontalAlignment="Left"  Click="btnCreationOffre_Click" Margin="0,2,0,8" Style="{DynamicResource nv_offreButton}"/>
        <Button Grid.Row="1" x:Name="btnModifierOffre" Background="Transparent" Width ="120" Height="35" BorderBrush="{x:Null}" HorizontalAlignment="Left" Click="btnModifierOffre_Click" Margin="130,2,0,8" Style="{DynamicResource modifierButton}" />
        <Button Grid.Row="1" x:Name="btnConsulterOffre" Width ="120" Height="35" Content="Consulter" HorizontalAlignment="left" Click="btnConsulterOffre_Click" Margin="260,2,0,8" Style="{DynamicResource consulterButton}" />
        <Button Grid.Row="1" x:Name="btnSuppOffre" Background="Transparent" Width ="120" Height="35" BorderBrush="{x:Null}" HorizontalAlignment="Left" Click="btnSuppOffre_Click" Margin="390,2,0,8" Style="{DynamicResource suppButton}" />
        <Rectangle HorizontalAlignment="Stretch" Fill="Gray" Height="2" Grid.Row="1" VerticalAlignment="Bottom" Grid.ColumnSpan="4" />

        <Grid x:Name="gridFocus" Grid.Row="2" Grid.ColumnSpan="4">

            <TextBlock Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">Numéro offre</TextBlock>
            <TextBox x:Name="textBoxNumOffre" Height="30" Grid.Row="0" Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Center" />

我想要的是当我打开这个用户控件时,我可以输入上面名为“textBoxNumOffre”的textboxshown

1 个答案:

答案 0 :(得分:0)

尝试将此添加到您在加载usercontrol时调用的方法(在xaml.cs中):

public YourUserControl()
{
    InitializeComponent();
    this.Dispatcher.BeginInvoke((Action)delegate
    {
        Keyboard.Focus(textBoxNumOffre);
    }, DispatcherPriority.Render);
}