C# 如何在Silverlight中创建数字文本框?

C# 如何在Silverlight中创建数字文本框?,c#,.net,silverlight,textbox,silverlight-2.0,C#,.net,Silverlight,Textbox,Silverlight 2.0,正如标题所说,真的。 我已经研究过从TextBox继承,但唯一合理的重写是“OnKeyDown”,但这只是从键枚举中给了我一个键(无法使用Char.IsNumeric())。看看工具箱中的NumericUpDown,也许你可以使用它或查看源代码来实现你自己的数字TextBox。看看这个,它在文本框上使用附加属性。我正在使用它,它确实有效。 private void Numclient\u KeyDown(对象发送方,KeyEventArgs e) { 如果(e.KeyKey.D9) { 如果(e

正如标题所说,真的。
我已经研究过从TextBox继承,但唯一合理的重写是“OnKeyDown”,但这只是从键枚举中给了我一个键(无法使用Char.IsNumeric())。

看看工具箱中的NumericUpDown,也许你可以使用它或查看源代码来实现你自己的数字TextBox。

看看这个,它在文本框上使用附加属性。我正在使用它,它确实有效。

private void Numclient\u KeyDown(对象发送方,KeyEventArgs e)
{
如果(e.KeyKey.D9)
{
如果(e.KeyKey.NumPad9)
{
if(e.Key!=Key.Back和&e.Key!=Key.Shift)
{
e、 已处理=正确;
}
}
}
}

我接受了Nidhal的建议答案,并对其进行了一些编辑,以处理数字以上字符的移位情况(即!@$%^&*),因为该解决方案仍然允许文本框中包含这些字符

private void NumClient_KeyDown(object sender, KeyEventArgs e)
{       
    // Handle Shift case
    if (Keyboard.Modifiers == ModifierKeys.Shift)
    {
       e.Handled = true;
    }

    // Handle all other cases
    if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9))
    {
        if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
        {
            if (e.Key != Key.Back)
            {
                e.Handled = true;
            }
        }
    }           
}
private void NumClient_KeyDown(对象发送方,KeyEventArgs e)
{       
//手柄变速箱
if(Keyboard.Modifiers==ModifierKeys.Shift)
{
e、 已处理=正确;
}
//处理所有其他案件
如果(!e.Handled&(e.KeyKey.D9))
{
如果(e.KeyKey.NumPad9)
{
if(e.Key!=Key.Back)
{
e、 已处理=正确;
}
}
}           
}
它可以工作:

static bool AltGrIsPressed;

void Numclient_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Alt)
    {
        AltGrIsPressed = false;
    }
}

void Numclient_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Alt)
    {
        AltGrIsPressed = true;
    }

    if (Keyboard.Modifiers == ModifierKeys.Shift || AltGrIsPressed == true)
    {
        e.Handled = true;
    }

    if (e.Handled == false && (e.Key < Key.D0 || e.Key > Key.D9))
    {
        if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)
        {
            if (e.Key != Key.Back)
            {
                e.Handled = true;
            }
        }
    }       
}
static bool AltGrIsPressed;
void Numclient_KeyUp(对象发送方,KeyEventArgs e)
{
if(e.Key==Key.Alt)
{
AltGrIsPressed=假;
}
}
void Numclient_KeyDown(对象发送方,KeyEventArgs e)
{
if(e.Key==Key.Alt)
{
AltGrIsPressed=真;
}
if(Keyboard.Modifiers==ModifierKeys.Shift | | AltGrIsPressed==true)
{
e、 已处理=正确;
}
if(e.Handled==false&(e.KeyKey.D9))
{
如果(e.KeyKey.NumPad9)
{
if(e.Key!=Key.Back)
{
e、 已处理=正确;
}
}
}       
}

扩展常规Silverlight文本框控件。在扩展文本框类中添加以下代码:

string nums = "1234567890";
string lastText = "";
int lastSelStart = 0;

protected override void TextChanged(object sender, TextChangedEventArgs e)
{
    if(!nums.Contains(this.Text.Substring(this.Text.Length -1)))
    {
         this.Text = lastText;
         this.SelectionStart = lastSelStart;
         return;
    }

    lastText = this.Text;
    lastSelStart = this.SelectionStart;

}

我知道它已经被回答了,但我没有找到处理所有特殊情况的合适解决方案,这里的大多数答案都会吞下一些重要的键,如Home、End、Tab、Shift+任何东西等等

因此,我开发了自己的实现,因为它可能会帮助某些人

public class IntegerTextBox : TextBox
    {
        /// <summary>
        /// To be raised whenever integer value changed
        /// </summary>
        public event EventHandler ValueChanged;

        /// <summary>
        /// To restore if the user entered invalid characters
        /// </summary>
        private int lastSavedValue = 0;

        private int lastSelectionStart = 0;
        private int lastSelectionLength = 0;


        public int IntegerValue
        {
            get
            {
                //the default value is 0 if there is no text in the textbox
                int value = 0;
                int.TryParse(Text, out value);
                return value;
            }
            set
            {
                if (this.Text.Trim() != value.ToString())
                {
                    Text = value.ToString();
                }
            }
        }

        public IntegerTextBox()
            : base()
        {
            this.LostFocus += (sender, e) =>
                {
                    //if the user clears the text the text box and leaves it, set it to default value
                    if (string.IsNullOrWhiteSpace(this.Text))
                        IntegerValue = 0;
                };
            this.Loaded += (sender, e) =>
                {
                    //populate the textbox with Initial IntegerValue (default = 0)
                    this.Text = this.IntegerValue.ToString();
                };

            this.TextChanged += (sender, e) =>
                {
                    int newValue = 0;
                    if (int.TryParse(this.Text, out newValue)) //this will handle most cases like number exceeds the int max limits, negative numbers, ...etc.
                    {
                        if (string.IsNullOrWhiteSpace(Text) || lastSavedValue != newValue)
                        {
                            lastSavedValue = newValue;
                            //raise the event
                            EventHandler handler = ValueChanged;
                            if (handler != null)
                                handler(this, EventArgs.Empty);

                        }
                    }
                    else 
                    {
                        //restore previous number
                        this.Text = lastSavedValue.ToString();
                        //restore selected text
                        this.SelectionStart = lastSelectionStart;
                        this.SelectionLength = lastSelectionLength;
                    }
                };

            this.KeyDown += (sender, e) =>
                {
                    //before every key press, save selection start and length to handle overwriting selected numbers
                    lastSelectionStart = this.SelectionStart;
                    lastSelectionLength = this.SelectionLength;
                };
        }
    } 
公共类IntegerTextBox:TextBox
{
/// 
///在整数值更改时提升
/// 
公共事件处理程序值已更改;
/// 
///在用户输入无效字符时还原的步骤
/// 
private int lastSavedValue=0;
private int lastSelectionStart=0;
private int lastSelectionLength=0;
公共整数值
{
得到
{
//如果文本框中没有文本,则默认值为0
int值=0;
int.TryParse(文本,输出值);
返回值;
}
设置
{
if(this.Text.Trim()!=value.ToString())
{
Text=value.ToString();
}
}
}
公共整数文本框()
:base()
{
this.LostFocus+=(发送方,e)=>
{
//如果用户清除文本框中的文本并将其保留,请将其设置为默认值
if(string.IsNullOrWhiteSpace(this.Text))
整数值=0;
};
此.Loaded+=(发件人,e)=>
{
//用初始IntegerValue(默认值=0)填充文本框
this.Text=this.IntegerValue.ToString();
};
this.TextChanged+=(发件人,e)=>
{
int newValue=0;
if(int.TryParse(this.Text,out newValue))//这将处理大多数情况,如数字超过int max限制、负数等等。
{
if(string.IsNullOrWhiteSpace(Text)| | lastSavedValue!=newValue)
{
lastSavedValue=新值;
//提出事件
EventHandler=ValueChanged;
if(处理程序!=null)
处理程序(此,EventArgs.Empty);
}
}
其他的
{
//恢复以前的号码
this.Text=lastSavedValue.ToString();
//还原所选文本
this.SelectionStart=lastSelectionStart;
this.SelectionLength=上次选择的长度;
}
};
this.KeyDown+=(发送方,e)=>
{
//每次按键前,保存选择开始和长度以处理覆盖选定数字的操作
lastSelectionStart=this.SelectionStart;
lastSelectionLength=this.SelectionLength;
};
}
} 

上面的代码有一个缺点,TextChanged事件会频繁出现,但是因为我们需要一个
整数
文本框,所以我们可以使用
ValueChanged

为什么每个人都不去努力处理这些问题呢

这里(这就是完美):


私有void文本框\u KeyDown(对象发送方,KeyEventArgs e)
{
var_Letter=string.Empty;
开关(电子钥匙)
{
案例编号:A:_Letter=“A”中断;
大小写键。添加:_Letter=“+”;中断;
案例
string nums = "1234567890";
string lastText = "";
int lastSelStart = 0;

protected override void TextChanged(object sender, TextChangedEventArgs e)
{
    if(!nums.Contains(this.Text.Substring(this.Text.Length -1)))
    {
         this.Text = lastText;
         this.SelectionStart = lastSelStart;
         return;
    }

    lastText = this.Text;
    lastSelStart = this.SelectionStart;

}
public class IntegerTextBox : TextBox
    {
        /// <summary>
        /// To be raised whenever integer value changed
        /// </summary>
        public event EventHandler ValueChanged;

        /// <summary>
        /// To restore if the user entered invalid characters
        /// </summary>
        private int lastSavedValue = 0;

        private int lastSelectionStart = 0;
        private int lastSelectionLength = 0;


        public int IntegerValue
        {
            get
            {
                //the default value is 0 if there is no text in the textbox
                int value = 0;
                int.TryParse(Text, out value);
                return value;
            }
            set
            {
                if (this.Text.Trim() != value.ToString())
                {
                    Text = value.ToString();
                }
            }
        }

        public IntegerTextBox()
            : base()
        {
            this.LostFocus += (sender, e) =>
                {
                    //if the user clears the text the text box and leaves it, set it to default value
                    if (string.IsNullOrWhiteSpace(this.Text))
                        IntegerValue = 0;
                };
            this.Loaded += (sender, e) =>
                {
                    //populate the textbox with Initial IntegerValue (default = 0)
                    this.Text = this.IntegerValue.ToString();
                };

            this.TextChanged += (sender, e) =>
                {
                    int newValue = 0;
                    if (int.TryParse(this.Text, out newValue)) //this will handle most cases like number exceeds the int max limits, negative numbers, ...etc.
                    {
                        if (string.IsNullOrWhiteSpace(Text) || lastSavedValue != newValue)
                        {
                            lastSavedValue = newValue;
                            //raise the event
                            EventHandler handler = ValueChanged;
                            if (handler != null)
                                handler(this, EventArgs.Empty);

                        }
                    }
                    else 
                    {
                        //restore previous number
                        this.Text = lastSavedValue.ToString();
                        //restore selected text
                        this.SelectionStart = lastSelectionStart;
                        this.SelectionLength = lastSelectionLength;
                    }
                };

            this.KeyDown += (sender, e) =>
                {
                    //before every key press, save selection start and length to handle overwriting selected numbers
                    lastSelectionStart = this.SelectionStart;
                    lastSelectionLength = this.SelectionLength;
                };
        }
    } 
<TextBox KeyDown="TextBox_KeyDown" />

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    var _Letter = string.Empty;
    switch (e.Key)
    {
        case Key.A: _Letter = "A"; break;
        case Key.Add: _Letter = "+"; break;
        case Key.Alt: break;
        case Key.B: _Letter = "B"; break;
        case Key.Back: break;
        case Key.C: _Letter = "C"; break;
        case Key.CapsLock: break;
        case Key.Ctrl: break;
        case Key.D: _Letter = "D"; break;
        case Key.D0: _Letter = "0"; break;
        case Key.D1: _Letter = "1"; break;
        case Key.D2: _Letter = "2"; break;
        case Key.D3: _Letter = "3"; break;
        case Key.D4: _Letter = "4"; break;
        case Key.D5: _Letter = "5"; break;
        case Key.D6: _Letter = "6"; break;
        case Key.D7: _Letter = "7"; break;
        case Key.D8: _Letter = "8"; break;
        case Key.D9: _Letter = "9"; break;
        case Key.Decimal: _Letter = "."; break;
        case Key.Delete: break;
        case Key.Divide: _Letter = "/"; break;
        case Key.Down: break;
        case Key.E: _Letter = "E"; break;
        case Key.End: break;
        case Key.Enter: break;
        case Key.Escape: break;
        case Key.F: _Letter = "F"; break;
        case Key.F1: break;
        case Key.F10: break;
        case Key.F11: break;
        case Key.F12: break;
        case Key.F2: break;
        case Key.F3: break;
        case Key.F4: break;
        case Key.F5: break;
        case Key.F6: break;
        case Key.F7: break;
        case Key.F8: break;
        case Key.F9: break;
        case Key.G: _Letter = "G"; break;
        case Key.H: _Letter = "H"; break;
        case Key.Home: break;
        case Key.I: _Letter = "I"; break;
        case Key.Insert: break;
        case Key.J: _Letter = "J"; break;
        case Key.K: _Letter = "K"; break;
        case Key.L: _Letter = "L"; break;
        case Key.Left: break;
        case Key.M: _Letter = "M"; break;
        case Key.Multiply: _Letter = "*"; break;
        case Key.N: _Letter = "N"; break;
        case Key.None: break;
        case Key.NumPad0: _Letter = "0"; break;
        case Key.NumPad1: _Letter = "1"; break;
        case Key.NumPad2: _Letter = "2"; break;
        case Key.NumPad3: _Letter = "3"; break;
        case Key.NumPad4: _Letter = "4"; break;
        case Key.NumPad5: _Letter = "5"; break;
        case Key.NumPad6: _Letter = "6"; break;
        case Key.NumPad7: _Letter = "7"; break;
        case Key.NumPad8: _Letter = "8"; break;
        case Key.NumPad9: _Letter = "9"; break;
        case Key.O: _Letter = "O"; break;
        case Key.P: _Letter = "P"; break;
        case Key.PageDown: break;
        case Key.PageUp: break;
        case Key.Q: _Letter = "Q"; break;
        case Key.R: _Letter = "R"; break;
        case Key.Right: break;
        case Key.S: _Letter = "S"; break;
        case Key.Shift: break;
        case Key.Space: _Letter = " "; break;
        case Key.Subtract: _Letter = "-"; break;
        case Key.T: _Letter = "T"; break;
        case Key.Tab: break;
        case Key.U: _Letter = "U"; break;
        case Key.Unknown: break;
        case Key.Up: break;
        case Key.V: _Letter = "V"; break;
        case Key.W: _Letter = "W"; break;
        case Key.X: _Letter = "X"; break;
        case Key.Y: _Letter = "Y"; break;
        case Key.Z: _Letter = "Z"; break;
        default: break;
    }
    var _Text = (sender as TextBox).Text + _Letter;
    double _Double;
    e.Handled = !double.TryParse(_Text, out _Double);
}
  using System;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Input;
  using System.Windows.Interactivity;

  namespace DataArtist
  {
public class NumericOnly : Behavior<TextBox>
{
    private string Text { get; set; }
    private bool shiftKey;
    public bool StripOnExit { get; set; }

    public NumericOnly()
    {
        StripOnExit = false;
    }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.KeyDown += KeyDown;
        AssociatedObject.KeyUp += KeyUp;
        AssociatedObject.GotFocus += GotFocus;
        AssociatedObject.LostFocus += LostFocus;
    }

    void KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Shift)
        {
            shiftKey = false;
        }
    }

    void KeyDown(object sender, KeyEventArgs e)
    {
        if (StripOnExit != false || e.Key == Key.Tab || e.Key == Key.Enter)
        {
            return;
        }

        if (e.Key == Key.Shift)
        {
            shiftKey = true;
        }
        else
        {
            if (IsNumericKey(e.Key) == false)
            {
                e.Handled = true;
            }
        }
    }

    void GotFocus(object sender, RoutedEventArgs e)
    {
        Text = AssociatedObject.Text;
    }

    private void LostFocus(object sender, RoutedEventArgs e)
    {
        if (AssociatedObject.Text == Text)
        {
            return;
        }

        string content = string.Empty;

        foreach (var c in AssociatedObject.Text)
        {
            if (Char.IsNumber(c) == true)
            {
                content += c;
            }
        }

        AssociatedObject.Text = content;
    }

    public bool IsNumericKey(Key key)
    {
        if (shiftKey == true)
        {
            return false;
        }

        string code = key.ToString().Replace("NumPad", "D");

        if (code[0] == 'D' && code.Length > 1)
        {
            return (Char.IsNumber(code[1]));
        }

        return false;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.KeyDown -= KeyDown;
        AssociatedObject.LostFocus -= LostFocus;
        AssociatedObject.GotFocus -= GotFocus;
    }
}   
    }
    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        bool isDigit = e.Key >= Key.D0 && e.Key < Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 ||
        e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9 ||e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right;

        if (isDigit) { }
        else
            e.Handled = true; 
    }