如何在实例化时将PreviewKeyDown事件附加到Dependencyobject?

时间:2016-02-16 14:22:35

标签: c# wpf xaml mvvm dependencyobject

我想在实例化时将PreviewKeyDown事件附加到我的dependencyobject。

代码:

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);
    }
}

现在我必须在事件绑定到依赖项对象之前更改文本框中的内容,但是如何在实例化时执行此操作?

基本问题是我只希望文本框接受小数,但这里有一个问题: 当我在文本框中键入TextChanged事件时会像这样:

  • 0 fire
  • 0,不要开火
  • 0,0 fire
  • 0,00 fire
  • 0 ,, 00不要开火

的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>

如果我将InputPrice属性更改为string,则每次都会触发TextChanged事件。

我希望通过按“,”按键来避免这种不一致。也许有更好的解决方案?

1 个答案:

答案 0 :(得分:0)