Reputation: 4057
I've added an Extended WPF Toolkit DoubleUpDown control. The behaviour is if you type 5.35 it is fine. Then say you type 4.3errortext7 and tab it reverts back to 5.35 (as the 4.3errortext7 is not a valid number).
However I'd like it just to go to 4.37 in that case (and ignore the invalid characters. Is there an elegant way to get my required behaviour?
Upvotes: 0
Views: 1835
Reputation: 4013
In my case, it was much better to use regex.
private void UpDownBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var upDownBox = (sender as DoubleUpDown);
TextBox textBoxInTemplate = (TextBox)upDownBox.Template.FindName("PART_TextBox", upDownBox);
Regex regex = new Regex("^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
e.Handled = !regex.IsMatch(upDownBox.Text.Insert((textBoxInTemplate).SelectionStart, e.Text));
}
Upvotes: 0
Reputation: 8111
Maybe a bit late but I had the same problem yesterday and I also did not want to register a handler every time I use the control. I mixed the solution by Mark Hall with an Attached Behavior
(inspired by this post: http://www.codeproject.com/Articles/28959/Introduction-to-Attached-Behaviors-in-WPF):
public static class DoubleUpDownBehavior
{
public static readonly DependencyProperty RestrictInputProperty =
DependencyProperty.RegisterAttached("RestrictInput", typeof(bool),
typeof(DoubleUpDownBehavior),
new UIPropertyMetadata(false, OnRestrictInputChanged));
public static bool GetRestrictInput(DoubleUpDown ctrl)
{
return (bool)ctrl.GetValue(RestrictInputProperty);
}
public static void SetRestrictInput(DoubleUpDown ctrl, bool value)
{
ctrl.SetValue(RestrictInputProperty, value);
}
private static void OnRestrictInputChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
DoubleUpDown item = depObj as DoubleUpDown;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool)e.NewValue)
item.PreviewTextInput += OnPreviewTextInput;
else
item.PreviewTextInput -= OnPreviewTextInput;
}
private static void OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!(char.IsNumber(e.Text[0]) ||
e.Text == CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))
{
e.Handled = true;
}
}
}
Then you can simply set the default style for DoubleUpDown
like this:
<Style TargetType="xctk:DoubleUpDown">
<Setter Property="behaviors:DoubleUpDownBehavior.RestrictInput" Value="True" />
</Style>
Upvotes: 0
Reputation: 54532
The best I was able to come up with is to use the PreviewTextInput Event and check for valid input, unfortunatly it will allow still allow a space between numbers, but will prevent all other text from being input.
private void doubleUpDown1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!(char.IsNumber(e.Text[0]) || e.Text== "." ))
{
e.Handled = true;
}
}
Upvotes: 1