I have been given this requirement to limit the text entered in a textbox/XamTextEditor to two lines. Unfortunately, I am not allowed to use a monospace/fixed widht font like 'Courier New' - I would have simply used the MaxLength property of the control. Instead I have to use a variable font, so the maxlength is unknown. MFC used to allow for this feature out of the box by simply not specifying a maxlength and not allowing for scrolling, but I don't see how to do this in WPF with an Infragistic XamTextEditor.
In this thread, Curtis Taylor showed how we can get the linecount as the user types text. I wrote a small prototype using this idea and when the linecount=3, I truncated the last character and set the textbox.text to the be the new truncated value.
This way I always have two lines and this kind of worked - unfortunately, when I set the textbox.text to the new string, the focus caret is placed at the beggining of the textbox. This obviously doesn't work since the user now continues typing from the beggining of the first line instead of not being able to type more characters at the end of the second line.
Curtis (or anyone else), do you have any idea on how I could handle this crazy requirement? I can post the XAML and code-behind if needed.
Rather than truncating the text, you should cancel the event so that the textbox never even knows about the keypress. You can use the PreviewKeyUp or PreviewKeyDown and set e.Handled=true if you've exceeded your max linecount.
<ig:XamTextEditor>
<ig:XamTextEditor.Resources>
<Style TargetType="{x:Type TextBox}">
<EventSetter Event="PreviewKeyUp" Handler="OnKeyUpOrDown"/>
<EventSetter Event="PreviewKeyDown" Handler="OnKeyUpOrDown"/>
</Style>
</ig:XamTextEditor.Resources>
</ig:XamTextEditor>
code:
private void OnKeyUpOrDown(object sender, KeyEventArgs e)
{
//if linecount exceeded
e.Handled = true;
}
Tony, thanks for the idea - it almost worked. I implemented what you suggested: when I type the next character that makes it linecount=3, I see that character, but I can no longer enter more text. At that point, I can't delete or type any additional characters since e.handled is being set to true, regardless.
Private Sub OnKeyUpOrDown(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Dim iLineCount As Integer = 0 Dim oTextBox As TextBoxIf TypeOf sender Is TextBox Then oTextBox = CType(sender, TextBox) iLineCount = oTextBox.LineCount If iLineCount > 2 Then e.Handled = TrueEnd If
End Sub
This was close - any other ideas?