2010-05-22 183 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(); 
     }; 
    } 
相關問題