【问题标题】:Moving to the end of the text in a readonly TextBox移动到只读文本框中的文本末尾
【发布时间】:2013-08-15 10:43:30
【问题描述】:

我的 WPF 应用程序中目前有一个只读的文本框:

<TextBox x:Name="TextBox_CurrentDirectory" IsReadOnly="True"></TextBox>

并且文本在后面的代码中得到更新:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var app = Application.Current as App;
    TextBox_CurrentDirectory.Text = app.ActiveDirectory;
    //Show the end of the text here
}

有没有办法让我以编程方式显示文本的结尾?如果 TextBox 中的文本比 TextBox 长,它只显示开头并被截断。我希望能够显示文本的结尾。

我尝试过使用

TextBox_CurrentDirectory.CaretIndex = TextBox_CurrentDirectory.Text.Length;

但什么也没发生。

【问题讨论】:

    标签: c# wpf xaml textbox readonly


    【解决方案1】:

    在设置 CaretIndex 之前,您需要给 TextBox 焦点。

    TextBox_CurrentDirectory.Text = app.ActiveDirectory;
    TextBox_CurrentDirectory.Focus();
    TextBox_CurrentDirectory.CaretIndex = TextBox_CurrentDirectory.Text.Length;
    

    【讨论】:

    • 感谢您指出这一点!修复了复制/粘贴问题。效果很好,非常感谢:)
    • 我认为 OP 只想显示文本的结尾而不关心插入符号的位置。所以只要打电话ScrollToEnd() 就可以了,不是吗?
    • @KingKing - 我也这么认为,但在我的测试中不起作用。我认为像这样调用ScrollToEnd 可能适用于多行文本框。
    • @miguelarcilla - 不客气 :) 刚刚更新了答案。如果在 CaretIndex 之前设置焦点,则根本不需要调用 ScrollToEnd。
    • @keyboardP 有道理,我想我忘了你需要专注于 TextBox 才能使插入符号发挥作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    相关资源
    最近更新 更多