How can I implement a Custom TextBox that accepts only decimals(positive and negative) in WinUI?
Tried implementing Custom TextBox that accepts only decimals(positive and negative) in WinUI but seems like WinUi doesn't have events like that in WPF.
Something like this should do the basics:
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace DecimalNumberBoxExample;
public sealed class DecimalNumberBox : TextBox
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
nameof(Value),
typeof(decimal?),
typeof(DecimalNumberBox),
new PropertyMetadata(null, OnValuePropertyChanged));
public DecimalNumberBox()
{
BeforeTextChanging += DecimalNumberBox_BeforeTextChanging;
TextChanging += DecimalNumberBox_TextChanging;
}
public decimal? Value
{
get => (decimal?)GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
private int NextCaretPosition { get; set; }
private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is DecimalNumberBox decimalNumberBox)
{
decimalNumberBox.Text = e.NewValue?.ToString() ?? string.Empty;
}
}
private void DecimalNumberBox_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
sender.SelectionStart = NextCaretPosition;
}
private void DecimalNumberBox_BeforeTextChanging(TextBox sender, TextBoxBeforeTextChangingEventArgs args)
{
if (string.IsNullOrEmpty(args.NewText) is true)
{
Value = null;
return;
}
if (decimal.TryParse(args.NewText, out decimal value) is false)
{
args.Cancel = true;
return;
}
NextCaretPosition = sender.SelectionStart;
Value = value;
}
}