2010-06-26 87 views
1

我在我的项目中使用了一个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设置最大长度?

回答

1

如何....

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(); 
    } 
} 
1

的问题可以通过从Control类,从中AutoCompleteBox派生子类,以这种方式来解决:

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); 
     } 
    } 
} 
相关问题