我正在开发一个用于货币编辑的自定义文本框。
我已经看到了一些可以立即使用的工具,但是它们很复杂和/或无法真正使用,迫使您采取不良做法(例如,硬编码应该在控件上使用的名称)。
因此,我决定自己进行操作,但是在绑定选项上却遇到了麻烦,因为分配给绑定属性的属性必须是十进制,但是TextBox控件的Text属性可以接受字符串。
我认为的答案可能是,重写对基类(TextBox)中Text属性的访问方法(getter和setter),但不允许这样做。
我的绑定应该设置为值,该值设置TextBox的text属性,可以随时随地将其格式化为文本(包含货币符号和所有内容),但可以在Get方法上将其转换回数字数据类型。
到目前为止,这是我实现的目标:
public class CurrencyTextBox : TextBox
{
private bool IsValidKey(Key key)
{
int k = (int)key;
return ((k >= 34 && k <= 43) //digits 0 to 9
|| (k >= 74 && k <= 83) //numeric keypad 0 to 9
|| (k == 2) //back space
|| (k == 32) //delete
);
}
private void Format()
{
//formatting decimal to currency text here
//Done! no problems here
}
private void FormatBack()
{
//formatting currency text to decimal here
//Done! no problems here
}
private void ValueChanged(object sender, TextChangedEventArgs e)
{
this.Format();
}
private void MouseClicked(object sender, MouseButtonEventArgs e)
{
this.Format();
// Prevent changing the caret index
this.CaretIndex = this.Text.Length;
e.Handled = true;
}
private void MouseReleased(object sender, MouseButtonEventArgs e)
{
this.Format();
// Prevent changing the caret index
this.CaretIndex = this.Text.Length;
e.Handled = true;
}
private void KeyPressed(object sender, KeyEventArgs e)
{
if (IsValidKey(e.Key))
e.Handled = true;
if (Keyboard.Modifiers != ModifierKeys.None)
return;
this.Format();
}
private void PastingEventHandler(object sender, DataObjectEventArgs e)
{
// Prevent copy/paste
e.CancelCommand();
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
// Disable copy/paste
DataObject.AddCopyingHandler(this, PastingEventHandler);
DataObject.AddPastingHandler(this, PastingEventHandler);
this.CaretIndex = this.Text.Length;
this.PreviewKeyUp += KeyPressed;
this.PreviewMouseDown += MouseClicked;
this.PreviewMouseUp += MouseReleased;
this.TextChanged += ValueChanged;
this.Format();
}
}
这是XAML:
<MyNamespace:CurrencyTextBox x:Name="TxbCurrency" Text="{Binding Path=DataContext.Element.Currency, ValidatesOnDataErrors=True}" />
到目前为止,一切都很好!从十进制属性到TextBox文本的绑定是“正确”。但是现在问题是如何在文本编辑后从文本中获取小数。
从十进制到.Text的绑定使用装箱隐藏ToString()方法。
问题在这里:在这种情况下,如何从十进制重载Parse()方法以使用FormatBack()方法从TextBox的Text获取十进制?
Dependency Property
像这样创建新的
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(
"Value",
typeof(decimal?),
typeof(CurrencyTextBox),
new FrameworkPropertyMetadata(
new decimal?(),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(ValuePropertyChanged)));
private static void ValuePropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
CurrencyTextBox x = (CurrencyTextBox)d;
x.Value = (decimal?)e.NewValue;
}
然后绑定到这个新属性
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句