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

查看:717
本文介绍了将插入符号/光标位置设置为字符串值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>


推荐答案

您可以使用 TextBox CaretIndex 属性。请记住,这不是 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 之后 文本属性,否则将无法使用。因此,如果你绑定到 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天全站免登陆