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?