将插入符号/光标位置设置为字符串值 WPF 文本框的末尾 [英] Set the caret/cursor position to the end of the string value WPF textbox

查看:31
本文介绍了将插入符号/光标位置设置为字符串值 WPF 文本框的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am try to set the caret/cursor position to the end of the string value in my WPF textbox when I open my window for the first time. I use the FocusManager to set the focus on my textbox when my window opens.

似乎没有任何效果.有什么想法吗?

Nothing seems to work. Any ideas?

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

Note, I am using the MVVM pattern, and I included only a portion of the XAML from my code.

<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>

推荐答案

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

You can set the caret position using CaretIndex property of a TextBox. Please bear in mind that this is not a DependencyProperty. Nevertheless, you may still set it in XAML like this:

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

请记住设置CaretIndex after Text 属性,否则将无法工作.因此,如果您像示例中那样绑定到 Text ,它可能无法工作.在这种情况下,只需像这样使用代码隐藏.

Please remember to set CaretIndex after Text property or else it will not work. Thus it probably won't work if you bind to Text like in your example. In that case, simply use code-behind like this.

NumberOfDigits.CaretIndex = NumberOfDigits.Text.Length;

这篇关于将插入符号/光标位置设置为字符串值 WPF 文本框的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆