且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

仅允许xaml.cs中的字符串值

更新时间:2022-10-16 13:29:19

除了字符串值之外,用户已经完全无法输入任何内容。案例结束。



但是,如果您只想允许用户输入的某些字符,并且如果您正在谈论某些文本框,你应该处理事件 System.Windows.Controls.Primitives.TextBoxBase.TextChanged

http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase。 textchanged.aspx [ ^ ]。



通过此活动,您有机会取消更改。请参阅:

http://msdn.microsoft .com / zh-cn / library / system.windows.controls.textchangedeventhandler.aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.windows.controls.textchangedeventargs.aspx [ ^ ]。



以下是如何:你需要将属性 System.Windows.Controls.TextChangedEventArgs.Handled 分配给true:

http://msdn.microsoft.com/en-us/lib rary / system.windows.routedeventargs.handled.aspx [ ^ ]。



你还要犯一个错误:过滤退格,即一些历史原因,被视为一个人物。它的代码点是8.允许它。

祝你好运,

-SA

I want to allow user to only enter string values in textbox but my code is not working well

string allowedCharacterSet = "bcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\b\n\t";

        if (allowedCharacterSet.Contains(e.Key.ToString() ))
        {

        }
        else
        {
            e.Handled = true;
        }

It is already totally impossible for a user to enter anything except a string value. Case closed.

However, if you want to allow only certain characters from your user input, and if you are talking about some text box, you should handle the event System.Windows.Controls.Primitives.TextBoxBase.TextChanged:
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.textboxbase.textchanged.aspx[^].

With this event, you have the opportunity to cancel the change. Please see:
http://msdn.microsoft.com/en-us/library/system.windows.controls.textchangedeventhandler.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.controls.textchangedeventargs.aspx[^].

Here is how: you need to assign the property System.Windows.Controls.TextChangedEventArgs.Handled to true:
http://msdn.microsoft.com/en-us/library/system.windows.routedeventargs.handled.aspx[^].

You are about to make one more mistake: to filter out backspace, which is, by some historical reasons, is considered as a character. Its code point is 8. Allow it, too.
Good luck,
—SA