2010-05-22 186 views
54

我尝试插入符/光标位置设置为我的WPF文本框中的字符串值的当我打开我的窗口,第一次。当我的窗口打开时,我使用FocusManager将焦点设置在我的文本框中。设置插入/光标位置到字符串值WPF文本框的末尾

似乎没有任何工作。有任何想法吗?

请注意,我使用的是MVVM模式,并且仅包含了代码中的一部分XAML。

<Window 
    FocusManager.FocusedElement="{Binding ElementName=NumberOfDigits}" 
    Height="400" Width="800"> 

    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition/> 
     </Grid.ColumnDefinitions> 
     <Grid.RowDefinitions> 
      <RowDefinition/> 
      <RowDefinition/> 
     </Grid.RowDefinitions> 

     <TextBox Grid.Column="0" Grid.Row="0" 
       x:Name="NumberOfDigits" 
       IsReadOnly="{Binding Path=IsRunning, Mode=TwoWay}" 
       VerticalContentAlignment="Center" 
       Text="{Binding Path=Digits, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
     <Button Grid.Column="0" Grid.Row="1" 
       Margin="10,0,10,0" 
       IsDefault="True" 
       Content="Start" 
       Command="{Binding StartCommand}"/> 
    </Grid> 
</Window> 

回答

76

您可以设置使用TextBoxCaretIndex财产的插入位置。请记住,这不是DependencyProperty。然而,你仍可以设置它在XAML这样的:

<TextBox Text="123" CaretIndex="{x:Static System:Int32.MaxValue}" /> 

请记得设置CaretIndexText财产,否则将无法正常工作。因此,如果您像在您的示例中那样绑定到Text,它可能不会起作用。在这种情况下,就像这样使用代码隐藏。

NumberOfDigits.CaretIndex = NumberOfDigits.Text.Length; 
+2

是的,我试图绑定到CaretIndex并失败。将代码添加到Window Loaded Event中的代码隐藏工作非常棒。 谢谢。 – Zamboni 2010-05-24 02:08:43

16

您也可以创建行为,尽管仍然存在代码隐藏,但它的优点是可重用。

例如简单的行为类,使用文本框的焦点事件:

class PutCursorAtEndTextBoxBehavior: Behavior<UIElement> 
{ 
    private TextBox _textBox; 

    protected override void OnAttached() 
    { 
     base.OnAttached(); 

     _textBox = AssociatedObject as TextBox; 

     if (_textBox == null) 
     { 
      return; 
     } 
     _textBox.GotFocus += TextBoxGotFocus; 
    } 

    protected override void OnDetaching() 
    { 
     if (_textBox == null) 
     { 
      return; 
     } 
     _textBox.GotFocus -= TextBoxGotFocus; 

     base.OnDetaching(); 
    } 

    private void TextBoxGotFocus(object sender, RoutedEventArgs routedEventArgs) 
    { 
     _textBox.CaretIndex = _textBox.Text.Length; 
    } 
}  

然后,在你的XAML中,附加的行为,像这样:

<TextBox x:Name="MyTextBox" Text="{Binding Value}"> 
     <i:Interaction.Behaviors> 
      <behaviors:PutCursorAtEndTextBoxBehavior/> 
     </i:Interaction.Behaviors> 
    </TextBox> 
+1

这是最好的解决方案。手动设置光标是一个痛苦的屁股。 – Darkhydro 2014-09-22 21:01:22

2

如果你的文本框(的WinForms)是一个垂直滚动条多,你可以试试这个:

textbox1.Select(textbox1.Text.Length-1, 1); 
textbox1.ScrollToCaret(); 

注:在WPF .ScrollToC aret()不是TextBox的成员。

1

如果多行TextBox设置光标不够。 试试这个:

NumberOfDigits.ScrollToEnd(); 
+0

只有代码答案不是很好的答案,添加几行来解释问题是什么以及代码如何修复它 – MikeT 2016-09-27 12:35:06

2

这对我有效。我也使用MVVM模式。不过,我使用MMVM的目的是让单元测试成为可能,并且更容易更新我的UI(松耦合)。我没有看到自己单元测试光标的位置,所以我不介意使用这个简单任务的代码。

public ExpeditingLogView() 
    { 
     InitializeComponent(); 

     this.Loaded += (sender, args) => 
     {         
      Description.CaretIndex = Description.Text.Length; 
      Description.ScrollToEnd(); 
      Description.Focus(); 
     }; 
    } 
相关问题