0

I want to attach PreviewKeyDown event to my dependencyobject on instatiation.

Code:

public class PriceFieldExtension : DependencyObject
{
    public static decimal GetPriceInputField(DependencyObject obj)
    {
        return (decimal)obj.GetValue(PriceInputFieldProperty);
    }

    public static void SetPriceInputField(DependencyObject obj, decimal value)
    {
        obj.SetValue(PriceInputFieldProperty, value);
    }

    public static readonly DependencyProperty PriceInputFieldProperty =
        DependencyProperty.RegisterAttached("PriceInputField", typeof (decimal), typeof (PriceFieldExtension), new FrameworkPropertyMetadata(0.00M, new PropertyChangedCallback(OnIsTextPropertyChanged)));

    private static void OnIsTextPropertyChanged(DependencyObject d,
        DependencyPropertyChangedEventArgs e)
    {

        TextBox targetTextbox = d as TextBox;
        if (targetTextbox != null)
        {
                targetTextbox.PreviewKeyDown += targetTextbox_PreviewKeyDown;
        }

    }
    static void targetTextbox_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        e.Handled = (e.Key == Key.Decimal);
    }
}

Right now i have to change something in the textbox before event is bound to the dependency object, but how can i do it on instantiation?

Ground problem is that i want textbox only to accept decimals, but here is a catch: When i type in the textbox TextChanged event fire like this:

  • 0 fire
  • 0, dont fire
  • 0,0 fire
  • 0,00 fire
  • 0,,00 dont fire

Xaml:

<TextBox Text="{Binding InputPrice, Mode=TwoWay,  UpdateSourceTrigger=PropertyChanged, StringFormat=F2}" Style="{StaticResource DefaultTextBox}" classes:PriceFieldExtension.PriceInputField="{Binding InputPrice, StringFormat=F2, Converter={StaticResource StringToDecimalConverter}}" TextAlignment="Right"  Margin="0,6,0,0" Height="45">
                        </TextBox>

if i change InputPrice property to be string, TextChanged event will fire every time.

I want to avoid this inconsistency by catching "," key press. Maybe there are better solutions?

Timsen
  • 4,066
  • 10
  • 59
  • 117
  • What about behavior? http://stackoverflow.com/a/8015485/5574010 – Anton Danylov Feb 16 '16 at 14:49
  • As a note, your PriceFieldExtension does not need to be derived from DependencyObject, because it only declares an attached property. It might instead be declared as `static class`, as all its members are static. – Clemens Feb 16 '16 at 14:51

1 Answers1

0

How about using a masked text box: https://marlongrech.wordpress.com/2007/10/28/masked-textbox/

unkreativ
  • 482
  • 2
  • 8