我想在实例化时将 PreviewKeyDown 事件附加到我的依赖对象。
代码:
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火
- 0,不开火
- 0,0 火
- 0,00 火
- 0,,00 不开火
xml:
<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 属性更改为字符串,则每次都会触发 TextChanged 事件。
我想通过捕捉“,”按键来避免这种不一致。也许有更好的解决方案?