[英]bug with custom control
我有一個自定義控件,它繼承自文本框控件。 除了一件事,它按預期工作。 當用戶輸入特殊字符時,光標將返回到文本框的第一個位置,而不是停留在剝離特殊字符的位置。 有想法該怎么解決這個嗎?
這是控件的完整代碼:
using System;
using System.Windows.Controls;
using System.Windows.Input;
namespace GamePresenter.XamlControls
{
class CleanTextBox : TextBox
{
#region Constructors
public CleanTextBox()
{
TextChanged += new TextChangedEventHandler(OnTextChanged);
KeyDown += new KeyEventHandler(OnKeyDown);
}
#endregion
#region Properties
new public String Text {
get { return base.Text; }
set {
base.Text = LeaveOnlyAlphaNumereicAndSpace(value);
}
}
#endregion
#region Functions
private bool isAlphaNumericOrKeypad(Key inKey)
{
//It will only enter the if statement if we are NOT dealing with alphanumeric
if ((inKey < Key.D0 || inKey > Key.D9) && (inKey < Key.A || inKey > Key.Z) && (inKey != Key.Space))
{
//Now check keypad keys.
if (inKey < Key.NumPad0 || inKey > Key.NumPad9)
{
return false;
}
}
return true;
}
private bool IsActionKey(Key inKey)
{
return inKey == Key.Delete || inKey == Key.Back || inKey == Key.Tab || inKey == Key.Return || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt);
}
private string LeaveOnlyAlphaNumereicAndSpace(String inString)
{
String tmp = inString;
foreach (char c in inString.ToCharArray())
{
if (!isAlphaNumeric(c))
{
tmp = tmp.Replace(c.ToString(), "");
}
}
return tmp;
}
public bool isAlphaNumeric(char c)
{
bool validFlag = false;
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == ' '))
{
validFlag = true;
}
else
{
validFlag = false;
}
return validFlag;
}
#endregion
#region Event Functions
protected void OnKeyDown(object sender, KeyEventArgs e)
{
e.Handled = !isAlphaNumericOrKeypad(e.Key) && !IsActionKey(e.Key);
}
protected void OnTextChanged(object sender, TextChangedEventArgs e)
{
base.Text = LeaveOnlyAlphaNumereicAndSpace(Text);
}
#endregion
}
}
有一種簡單的方法可以解決您的問題,而無需更改很多代碼。 如下所示,在textchanged
事件中重置插入符號索引。
protected void OnTextChanged(object sender, TextChangedEventArgs e)
{
//GET YOUR CARET INDEX
int cIndex = textbox.CaretIndex;
textbox.Text = LeaveOnlyAlphaNumereicAndSpace(textbox.Text);
//SET YOUR CARET INDEX
textbox.CaretIndex = cIndex;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.