【发布时间】:2015-01-15 21:22:53
【问题描述】:
我正在开发用于货币编辑的自定义文本框。
我见过一些现成的,但它们很复杂和/或不是真正可用的,迫使您采取不良做法(例如硬编码应该在控件上使用的名称)。
所以我决定自己做,但我无法使用绑定选项,因为分配给绑定属性的属性必须是小数,但 TextBox 控件的 Text 属性接受字符串。
我想的答案是,也许将访问方法(getter 和 setter)覆盖到基类(TextBox)中的 Text 属性,但这是不允许的。
我的绑定应该设置为值,它将 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 的文本中获取小数?
【问题讨论】:
-
我想让用户输入任何文本,即使是字符串,如果他没有添加十进制值,当失去焦点时会调用
-
我猜这个问题不清楚。问题在于绑定,而不是格式化逻辑。格式化文本已经可以了...
-
如果是这种情况,创建新的
Dependency Property调用它的值并将你的货币绑定到它
标签: c# wpf xaml binding custom-controls