I'm studying about TextBox
in C # and I have no idea how to do this function.
I'm studying about TextBox
in C # and I have no idea how to do this function.
In the .xaml
file of your Window
, place the following code. What matters here is the KeyDown="txtTest_KeyDown"
event:
<TextBox x:Name="txtTest" KeyDown="txtTest_KeyDown" HorizontalAlignment="Left" Height="23" Margin="239,148,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="282"/>
Now, in the% w of% of your% w%, create the% w% method as follows:
private void txtTest_KeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.S || e.Key == Key.N)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
What happens immediately is to intercept the key pressed, using the KeyDown
event, and check which one it was.
If the key corresponds to S or N the implementation should return e.Handled = false;
, otherwise return e.Handled = true;
.
Unfortunately this is not enough, since the space key is not intercepted. On the other hand there is the possibility that the text can be entered via paste .
So, to deal with all possibilities, you should treat the following events:
and restrict the number of accepted characters to 1.
The "best" way to implement is to write a custom TextBox that you can use anywhere.
public class S_N_TextBox : TextBox
{
public S_N_TextBox()
{
DataObject.AddPastingHandler(this, PastingHandler);
MaxLength = 1;
}
private void PastingHandler(object sender, DataObjectPastingEventArgs e)
{
var pasteText = e.DataObject.GetData(typeof(string)) as string;
//Garante que o texto inserido via paste é válido
if (!IsValid(pasteText))
{
e.CancelCommand();
}
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
{
if (IsValid(e.Text))
{
//A documentação recomenda que o método base seja chamado.
base.OnPreviewTextInput(e);
return;
}
e.Handled = true;
}
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
//Não permite o uso do espaço
e.Handled = e.Key == Key.Space;
}
//Determina que texto pode ser aceite
protected virtual bool IsValid(string input) => input == "S" || input == "N";
}
This class can be used as the basis for other restrictions that you want a TextBlox to have. You only need to change the IsValid
() method.