我在我的项目中使用AutoCompleteBox控件。现在,我需要限制用户可以输入的文本长度,例如最大长度为50个字符。在这种情况下,TextBox有MaxLength属性,而AutoCompleteBox没有。而且,AutoCompleteBox不公开TextBox的属性。
我试着这样解决这个问题:
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设置最大长度吗?
发布于 2011-03-01 01:18:14
怎么样..。
public class CustomAutoCompleteBox : AutoCompleteBox
{
private int _maxlength;
public int MaxLength
{
get
{
return _maxlength;
}
set
{
_maxlength = value;
if (tb != null)
tb.MaxLength = value;
}
}
TextBox tb;
public override void OnApplyTemplate()
{
tb = this.GetTemplateChild("Text") as TextBox;
base.OnApplyTemplate();
}
}发布于 2010-07-01 05:37:04
这个问题可以通过从Control类派生子类来解决,AutoCompleteBox是从Control类派生出来的,方法如下:
public class AutoCompleteBoxMaxLengthed : AutoCompleteBox
{
public int MaxLength
{
get;
set;
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (Text.Length >= MaxLength)
{
e.Handled = true;
}
else
{
base.OnKeyDown(e);
}
}
}https://stackoverflow.com/questions/3125446
复制相似问题