【问题标题】:TextBox.TextAlign right-side alignment has no effect in certain conditions?TextBox.TextAlign 右侧对齐在某些情况下没有效果?
【发布时间】:2013-03-13 07:55:42
【问题描述】:

我的 Visual C# Express 2010 表单应用程序中有一个路径选择器。

我使用FolderBrowserDialog 和(单行)TextBox 来显示所选路径。在我的 UI 刷新代码中使用以下行。

this.textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;

ReadOnly 属性设置为 true 并且 TextAlign 属性设置为 Right 使用表单设计器,因为选择的路径通常比文本框长,我更喜欢显示路径的右侧。表单设计器会生成这个:

// 
// textBoxFolder
// 
this.textBoxFolder.Location = new System.Drawing.Point(40, 72);
this.textBoxFolder.Name = "textBoxFolder";
this.textBoxFolder.ReadOnly = true;
this.textBoxFolder.Size = new System.Drawing.Size(160, 20);
this.textBoxFolder.TabIndex = 13;
this.textBoxFolder.TabStop = false;
this.textBoxFolder.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

只要选择的路径短于文本框大小,右对齐就会起作用。 (但这并不重要)

Whenever the chosen path is longer than the textbox size, the Right alignment has no effect, the string in the textbox is displayed such that the left-most character is visible, and right-most are hidden.

我知道在普通的单行文本框 (ReadOnly = false) 中,当手动输入过长的字符串时,即使焦点消失,最右边的字符也是可见的,无论如何 TextAlign 是否设置为左/右/居中!

换句话说,我的目标是,当 TextBox.Text 以编程方式设置(而不是输入)并且字符串长于 TextBox 的宽度时,如何让最右边的字符可见?

【问题讨论】:

    标签: c# winforms visual-studio-2010


    【解决方案1】:

    您应该将插入符号移到最后一个字符,而不是设置 TextAlign 属性:

    textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;
    textBoxFolder.SelectionStart = textBox1.Text.Length - 1;
    

    设置SelectionStart 实际上将插入符号移动到指定位置。这使得该位置的字符在TextBox 中可见。

    如果您可以使用Label 代替文本框,则可以在绘制文本时使用one created by Hans Passant here,它使用TextFormatFlags.PathEllipses 标志。

    【讨论】:

    • 谢谢!设置 SelectionStart 正是我想要的!
    • 请注意,如果有可能出现空字符串,那么您可能需要类似 textBoxFolder.SelectionStart = Math.Max(0, textBox1.TextLength-1);
    【解决方案2】:

    Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows CE Platform 注意:在基于 Pocket PC 的应用程序中,单行文本框仅支持左对齐。多行文本框可以左对齐、右对齐或居中对齐。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多