我在我的项目中使用了一个AutoCompleteBox控件。现在我需要限制用户可以输入的文本的长度,例如最长50个字符。对于这种情况,TextBox具有MaxLength属性,但AutoCompleteBox没有。此外,AutoCompleteBox不公开TextBox的属性。MaxLength for Silverlight中的AutoCompleteBox
我试图解决的问题是这样的:
private void autoCompleteBox_TextChanged(object sender, RoutedEventArgs e)
{
AutoCompleteBox autoCompleteBox = sender as AutoCompleteBox;
if (autoCompleteBox.Text.Length > MaxCharLength)
{
autoCompleteBox.Text = autoCompleteBox.Text.Substring(0, MaxCharLength);
}
}
这种方法的一大缺点是设置Text属性之后,文本框中插入符号复位到起始位置,当用户继续打字,最后的字符被剪裁,并且插入符号总是会开始。 没有暴露控制插入符的方法(如TextBox的Select方法)。
任何想法如何可以为AutoCompleteBox设置最大长度?