Adapting WPF to allow a numeric textbox in WPF sounds very trivial, but it is not! A user friendly textbox in WPF couldhave different aspects.
It could be possible to:
- Only allow numbers or decimal separator
- Possible to specify number of digits for integer part and number of digits for decimal part
- Specify an empty default value
- Still rely on default components such as WPF Textbox
The following WPF Converter allows to restrict user input using ConvertBack method. Usually a developer implements the Convert method to transform output,
here we use ConvertBack to filter input to only allow numbers or decimal separator.
NumericFormatConverter
using Hemit.OpPlan.Common;
using System;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows.Data;
namespace Hemit.OpPlan.Client.Infrastructure.Converters
{
public class NumericFormatConverter : IValueConverter
{
public int IntegerLength { get; set; }
public int DecimalLength { get; set; }
public string DefaultValue { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DefaultValue;
string adjustedValue = AdjustValueToAcceptingFormat(value.ToString());
return adjustedValue;
}
private string AdjustValueToAcceptingFormat(string value)
{
if (string.IsNullOrEmpty(value))
return DefaultValue;
char decimalSeparator = Thread.CurrentThread?.CurrentCulture?.NumberFormat?.NumberDecimalSeparator.ToCharArray().First() ?? ',';
string[] compounds = value.Split(new[] { decimalSeparator });
if (compounds.Length <= 0)
{
return DefaultValue; //default to zero
}
if (compounds.Length == 1)
{
return NumericDigits(compounds[0], decimalSeparator);
}
return $"{NumericDigits(compounds[0], decimalSeparator).Truncate(3)}{decimalSeparator}{NumericDigits(compounds[1], decimalSeparator).Truncate(1)}";
}
private static string NumericDigits(string input, char decimalSeparator)
{
return string.Join("", input.ToCharArray().Where(ch => Char.IsDigit(ch) || ch == decimalSeparator)).Truncate(3);
}
}
}
If you rely on MVVM, you can bind up a numeric value with a proxy property with datatype string for flexible input.
[State]
[NotifyPropertyChanged(true)]
[AffectsOtherProperty("BodyMassIndex")]
[Range(0.0, 500, ErrorMessage = @"Max Weight is surpassed")]
public double? Weight { get; set; }
private string _weightInputValue;
public string WeightInputValue
{
get { return _weightInputValue; }
set
{
if (_weightInputValue != value)
{
_weightInputValue = value;
double weight;
if (double.TryParse(_weightInputValue, out weight))
{
Weight = weight;
}
RaisePropertyChanged(() => WeightInputValue);
}
}
}
Never mind the Postsharp aspects for State, NotifyPropertyChanged and AffectsOtherProperty listed here, they are not necessary in your use case. But shows a real world scenario.
In WPF frontend you can then bind up the WPF converter like this:
<TextBlock Grid.Row="7" Grid.Column="2" Margin="2" Text="Vekt (kg)" VerticalAlignment="Center" HorizontalAlignment="Left" />
<TextBox Grid.Row="7" Grid.Column="4" MaxLength="5" Height="24" behaviors:TextBoxRegExBehavior.RegularExpressionProperty="^\d+[,|.]*\d*$" FontWeight="Normal"
HorizontalAlignment="Left"
behaviors:TextBoxRegExBehavior.MaxLength="5" behaviors:TextBoxRegExBehavior.MustParseToType="{x:Type sys:Double}" behaviors:TextBoxRegExBehavior.EmptyValue="0"
Margin="2,2,2,2" Width="40" Text="{Binding WeightInputValue, Converter={StaticResource numericFormatConverter}, ConverterCulture={x:Static gl:CultureInfo.CurrentCulture}, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=true}"
Style="{StaticResource ReadOnlyTextBoxStyleHidingZero}" IsReadOnly="{Binding IsEditMode, Converter={StaticResource invertedBoolConverter}}" TabIndex="35" />
Again, much custom stuff here, but the key thing to notice is that you only need to make sure you bind against the proxy property of type string, the WPF converter numericFormatConverter handles the formatting of the input.
<converters:NumericFormatConverter x:Key="numericFormatConverter" IntegerLength="3" DecimalLength="1" DefaultValue=""></converters:NumericFormatConverter>
Share this article on LinkedIn.
No comments:
Post a Comment