Replies: 1 comment
-
You should use some preview events here. You can wrap them into a reusable attached behavior if you want. The following will block any numeric digits from entering the <TextBox x:Name="box" /> public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
box.AddHandler(TextInputEvent, Box_TextInput, Avalonia.Interactivity.RoutingStrategies.Tunnel);
box.PastingFromClipboard += Box_PastingFromClipboard;
}
private async void Box_PastingFromClipboard(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
if (GetTopLevel(this)?.Clipboard is not { } clipboard)
return;
e.Handled = true; // Never allow the default handler to handle pastes
try
{
var text = await clipboard.GetTextAsync();
if (!text.Any(char.IsDigit))
box.Text += text;
}
catch (TimeoutException)
{
// Silently ignore.
}
}
private void Box_TextInput(object? sender, Avalonia.Input.TextInputEventArgs e)
{
if (e.Text!.Any(char.IsDigit))
{
e.Handled = true;
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
In the TextBox control, I am trying to handle to the TextChanging event and check for invalid characters (only a custom set of characters are allowed). If any are found, I tried to set the event's Handled property to true to prevent the character from being rendered. However, this did not work; The character was still rendered.
Does the Handled property not work in the same way it does for WPF?
Beta Was this translation helpful? Give feedback.
All reactions