【发布时间】:2016-05-27 21:04:00
【问题描述】:
我想在实例化时将 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 不要开火
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 事件。
我想通过捕捉“,”键来避免这种不一致。也许有更好的解决方案?
【问题讨论】:
-
请注意,您的 PriceFieldExtension 不需要从 DependencyObject 派生,因为它只声明了一个附加属性。它可能被声明为
static class,因为它的所有成员都是静态的。
标签: c# wpf xaml mvvm dependencyobject