85

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

似乎没有任何效果。有任何想法吗?

请注意,我使用的是 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>
4

10 回答 10

117

您可以使用CaretIndexa 的属性设置插入符号的位置TextBox。请记住,这不是DependencyProperty. 尽管如此,您仍然可以像这样在 XAML 中设置它:

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

请记住CaretIndex Text属性之后设置,否则它将不起作用。Text因此,如果您在示例中绑定到 like,它可能不起作用。在这种情况下,只需像这样使用代码隐藏。

NumberOfDigits.CaretIndex = NumberOfDigits.Text.Length;
于 2010-05-23T18:52:52.050 回答
26

您还可以创建一个 Behavior,它虽然仍然是代码隐藏的,但具有可重用的优势。

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

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>
于 2013-08-21T20:04:32.470 回答
5

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

    public ExpeditingLogView()
    {
        InitializeComponent();

        this.Loaded += (sender, args) =>
        {                                
            Description.CaretIndex = Description.Text.Length;
            Description.ScrollToEnd();
            Description.Focus();
        };
    }
于 2017-06-09T14:04:36.777 回答
3

textbox如果在模板绑定或任何类型的惰性绑定或惰性值分配中使用@Louis 解决方案将不起作用

因此,如果textbox在 Datagrid 单元格中用作模板,则该解决方案将需要进行微小的修改才能工作

那就是订阅文本更改事件

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

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

            _textBox = AssociatedObject as TextBox;

            if (_textBox == null)
            {
                return;
            }
            _textBox.GotFocus += TextBoxGotFocus;
            // to make it work with binding
            _textBox.TextChanged += TextBoxGotFocus;
        }

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

            base.OnDetaching();
        }

        private void TextBoxGotFocus(object sender, RoutedEventArgs routedEventArgs)
        {
            _textBox.CaretIndex = _textBox.Text.Length;
        }
    }
于 2020-05-12T05:11:27.747 回答
3

在多行TextBox设置光标不够的情况下。尝试这个:

NumberOfDigits.ScrollToEnd();
于 2016-09-26T11:41:34.510 回答
3

在 WPF 中,如果行足够长,滚动到行尾也很重要。所以我使用以下几行:

text_Box.Text = text;
text_Box.CaretIndex = text.Length;
text_Box.ScrollToHorizontalOffset(double.MaxValue);
// or you can use this - for me works also
// text_Box.ScrollToHorizontalOffset(text_Box.GetRectFromCharacterIndex(openFileDialog.FileName.Length).Right);

但请阅读此警告(对我来说很好 - 可能已经修复): TextBox ScrollToHorizo​​ntalOffset will not scroll after text is enough long

于 2019-11-08T19:58:25.030 回答
2

这里没有一个答案对我有用。我正在为 TextBox 使用绑定,并且需要在窗口弹出后立即移动插入符号。这为我做到了:

public MyWindow()
{
    InitializeComponent();

    ContentRendered += (sender, args) =>
    {
        MyTextBox.CaretIndex = MyTextBox.Text.Length;
        MyTextBox.ScrollToEnd(); // not necessary for single line texts
        MyTextBox.Focus();
    };
}

类似于 Ceranski 的回答。我们添加到的不是添加到Loaded事件中ContentRendered

于 2019-12-18T08:45:08.383 回答
0

我想创建一个用户控件/视图,其中预先填充了一个绑定到 ViewModel 的文本框,当控件打开时,焦点会自动设置在文本框和末尾的插入符号位置上。这是我让它工作的唯一方法:

public TextBoxDialogView()
{
    InitializeComponent();

    TextBox.GotKeyboardFocus += (sender, args) =>
    {
        TextBox.CaretIndex = TextBox.Text.Length;
    };
    _ = TextBox.Focus();
}

到目前为止似乎工作得很好......

于 2021-07-08T13:22:57.410 回答
0

由于某些原因,我不得不使用:

Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => 
{
    textBox.CaretIndex = textBox.Text.Length;
    textBox.ScrollToEnd();
}));
于 2021-02-18T12:46:48.220 回答
0

试试这个给定的方法: https ://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/position-the-cursor-at-the-beginning-or-end-of-text?view=netframeworkdesktop -4.8

textBox.Select(2,0);
于 2021-05-14T12:06:57.247 回答