我想将 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);
}
}
现在,在事件绑定到依赖项对象之前,我必须在文本框中更改某些内容,但是如何在实例化时执行此操作?
基本问题是我只希望文本框接受小数,但这里有一个问题:当我在文本框中输入文本更改事件时,会像这样触发:
- 0 火灾
- 0、不开火
- 0,0 火灾
- 0,00 火
- 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 属性更改为字符串,则每次都会触发 TextChanged 事件。
我想通过捕获","按键来避免这种不一致。也许有更好的解决方案?
如何使用屏蔽文本框:https://marlongrech.wordpress.com/2007/10/28/masked-textbox/