【发布时间】:2015-05-07 01:30:43
【问题描述】:
我有一个具有 AcceptsReturn = True 的文本框。当用户按下回车键时,新行的第一个字母“-”已经存在。 我该怎么做?
【问题讨论】:
我有一个具有 AcceptsReturn = True 的文本框。当用户按下回车键时,新行的第一个字母“-”已经存在。 我该怎么做?
【问题讨论】:
步骤 1:编写一个方法来检测 Key Press 上“Return”键的按下情况。
第 2 步:在 TextBox 的.text 中添加一个“-”。
【讨论】:
关注PreviewKeyDown 事件:
<TextBox PreviewKeyDown="UIElement_OnKeyDown"
AcceptsReturn="True"
x:Name="TextBox"
</TextBox>
private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// what u need
// TextBox.Text += "-";
}
}
【讨论】:
可能还有其他更聪明的方法可以做到这一点,但一个简单的解决方案是将 PreviewKeyDown 添加到 TextBox。 (注意:接受返回 KeyDown 不会触发它由文本框处理。)
PreviewKeyDown="TextBox_KeyDown"
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Return)
{
(sender as TextBox).Text += "-";
}
}
这应该在新行中添加一个 -。
【讨论】:
订阅TextBox KeyDown事件并检测Enter是否被按下:
XAML:
<TextBox ... KeyDown="TextBox_KeyDown"/>
C#:
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
TextBox txtBox = sender as TextBox;
txtBox.Text += Environment.NewLine + "-"; //add new line and "-"
txtBox.CaretIndex = txtBox.Text.Length; //caret to the end
}
}
要使用此方法,您必须 false Accept Return 属性。
【讨论】:
false它才能使用这个方法。
- 的新行。这是他的方法,我提供了另一种方法。当解决方案与问题无关时,您应该投反对票。