【问题标题】:WPF - set focus on textboxWPF - 将焦点放在文本框上
【发布时间】:2015-01-05 10:14:45
【问题描述】:

在我的WPF 应用程序中,我在一页上有很多文本框。我想将焦点放在第一个文本框上。我用谷歌搜索并尝试了不同的解决方案。

XAML 代码:

<StackPanel Width="350" HorizontalAlignment="Left" >
    <TextBlock x:Name="CustNamelbl" Text="C U S T O M E R  N A M E"
               Style="{StaticResource LightBoldTxtblkStyle }"/>
    <Grid Height="35">
         <TextBox x:Name="CustName" Style="{StaticResource Txtbox}"
                  LostFocus="CustName_LostFocus_1"   TabIndex="1"
                  CommandManager.PreviewExecuted="CustName_PreviewExecuted"
                  ContextMenu="{x:Null}" PreviewTextInput="CustName_PreviewTextInput"
                  Margin="0,0,0,0" GotFocus="CustName_GotFocus"/>
         <Rectangle Fill="White" Height="2" Opacity="0.2" 
                    VerticalAlignment="Bottom"></Rectangle>
   </Grid>
</StackPanel>   

C# 代码:

CustName.Focus();
Keyboard.Focus(CustName);

使用此代码,我在 TextBox 上得到了 Focus。我还可以打开系统键盘。但是,我无法在 TextBox 中输入任何内容。此外,该聚焦光标不是闪烁光标,而只是稳定光标。

【问题讨论】:

  • 尝试将焦点设置在加载的事件处理程序上。我的猜测是你在构造函数中设置焦点。有关更多详细信息,请阅读:WPF Input Focus Overview
  • 我认为问题在于CustName_GotFocus。现在尝试从xaml 中删除该方法,看看是否有帮助。

标签: c# wpf xaml


【解决方案1】:

给你的TextBox 起个名字,然后你就可以调用你的 Window-Tag

FocusManager.FocusedElement="{Binding ElementName=YOURTBNAME}"

【讨论】:

  • 非常不错的纯 xaml,不知道我们可以这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 2012-11-02
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多