title: How to attach PreviewKeyDown event to Dependencyobject on instantiation?
body: <p>I want to attach PreviewKeyDown event to my dependencyobject on instatiation.</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><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);
      }
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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:</p>
  
  <ul>
  <li>0  fire    </li>
  <li>0, dont fire </li>
  <li>0,0   fire </li>
  <li>0,00  fire  </li>
  <li>0,,00 dont fire</li>
  </ul>
  
  <p><strong>Xaml:</strong></p>
  
  <pre><code>&lt;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"&gt;
                          &lt;/TextBox&gt;
  </code></pre>
  
  <p>if i change InputPrice property to be string, TextChanged event will fire every time.</p>
  
  <p>I want to avoid this inconsistency by catching "," key press. Maybe there are better solutions?</p>