当文本框的属性Enabled
被设置为false或只读属性被设置为true时,显示的文本会呈现黑色底纹,这样并不方便阅读。
在Windows Forms中,有什么最简单的方法能够漂亮地展示只读文本呢?
当控件被锁定时,您无法覆盖ForeColor和BackColor属性吗?
如果无法实现,可以创建自己的文本框类来监听KeyUp事件,并在ReadOnly(或Locked)属性设置为true时拦截按键(防止其添加到文本中)。然后,您可以使用任何样式。
BackColor = SystemColors.Window
和 ForeColor = SystemColors.ControlText
。 - Oliver在Windows上,这似乎是一件非常糟糕的事情,具体取决于你想要达到的程度(例如,如果你希望文本可选择或不可选择,如果你希望能够进行文本格式设置)。
我在一段时间前发现了这个问题,但很幸运地在各种博客上找到了相当好的文档。看起来你可以使用RichTextBox,但创建事件处理程序以防止最终用户修改其内容。
例如,称为“myRichTextBox”的RichTextBox,然后您将希望在窗体的Designer.cs中添加以下内容:
this.myRichTextBox.SelectionChanged += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.DoubleClick += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.GotFocus += new System.EventHandler(this.MyRichTextBox_Deselect);
this.myRichTextBox.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.MyRichTextBox_LinkClicked);
然后您需要在表单中创建以下类似的方法:
public void MyRichTextBox_Deselect(object sender, EventArgs e)
{
// When user tries to select text in the rich text box,
// set selection to nothing and set focus somewhere else.
RichTextBox richTextBox = sender as RichTextBox;
richTextBox.SelectionLength = 0;
richTextBox.SelectionStart = richTextBox.Text.Length;
// In this case I use an instance of separator bar on the form to switch focus to.
// You could equally set focus to some other element, but take care not to
// impede accessibility or visibly highlight something like a label inadvertently.
// It seems like there should be a way to drop focus, perhaps to the Window, but
// haven't found a better approach. Feedback very welcome.
mySeperatorBar.Focus();
}
public void MyRichTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(e.LinkText);
}
显然,您可能不关心LinkClickedEventHandler()处理程序,但我确认希望具有此功能是相当普遍的,因为RichTextBox控件具有自动识别和着色URL的选项。
我不知道为什么似乎没有更优雅的解决方案,欢迎任何了解更好方法的人提供意见。
嗯... 使用标签? 为什么要使用文本框,并使其看起来可编辑,而实际上它并不是? 你想让用户感到困惑吗? 违反惯例的用户界面风格习语,自行承担风险。