using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; namespace CustomControls { [DesignTimeVisible(false)] public partial class NumericUpDown : UserControl, INotifyPropertyChanged { public NumericUpDown() { InitializeComponent(); } public event PropertyChangedEventHandler PropertyChanged; public decimal Maximum { get { return (decimal)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } public readonly static DependencyProperty MaximumProperty = DependencyProperty.Register( "Maximum", typeof(decimal), typeof(NumericUpDown), new UIPropertyMetadata(100m)); public decimal Minimum { get { return (decimal)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } public readonly static DependencyProperty MinimumProperty = DependencyProperty.Register( "Minimum", typeof(decimal), typeof(NumericUpDown), new UIPropertyMetadata(0m)); public decimal Value { get { return (decimal)GetValue(ValueProperty); } set { SetCurrentValue(ValueProperty, value); } } public readonly static DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(decimal), typeof(NumericUpDown), new UIPropertyMetadata(0m, (o, e) => { NumericUpDown tb = (NumericUpDown)o; tb.RaiseValueChangedEvent(e); })); public event EventHandler ValueChanged; private void RaiseValueChangedEvent(DependencyPropertyChangedEventArgs e) { ValueChanged?.Invoke(this, e); } public decimal Increment { get { return (decimal)GetValue(IncrementProperty); } set { SetValue(IncrementProperty, value); } } public readonly static DependencyProperty IncrementProperty = DependencyProperty.Register( "Increment", typeof(decimal), typeof(NumericUpDown), new UIPropertyMetadata(1m)); public int DecimalPlaces { get { return (int)GetValue(DecimalPlacesProperty); } set { SetValue(DecimalPlacesProperty, value); } } public static readonly DependencyProperty DecimalPlacesProperty = DependencyProperty.Register( "DecimalPlaces", typeof(int), typeof(NumericUpDown), new PropertyMetadata(0)); public string FormattedValue { get => Value.ToString("N" + DecimalPlaces.ToString()); set { if (decimal.TryParse(value, out decimal d)) Value = d; } } protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) { base.OnPropertyChanged(e); if (e.Property.Name == "Value" || e.Property.Name == "DecimalPlaces") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("FormattedValue")); } } private void btnUp_Click(object sender, RoutedEventArgs e) { if (Value < Maximum) { Value += Increment; if (Value > Maximum) Value = Maximum; } } private void btnDown_Click(object sender, RoutedEventArgs e) { if (Value > Minimum) { Value -= Increment; if (Value < Minimum) Value = Minimum; } } private void tbmain_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) { if (e.Key == System.Windows.Input.Key.Enter) { ((TextBox)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource(); } } } }