[英]WPF: formatting textbox input as user types
在我們的WPF應用程序中,有幾個文本框,用戶應僅輸入貨幣。 強制文本框在輸入內容時對其進行格式化很容易:
<TextBox Text="{Binding CostOut, StringFormat='{}{0:C}' />
但是,這種格式設置的速度如此之快,以至於在鍵入文本時都會給用戶帶來意想不到的效果,因為小數點前后的數字似乎幾乎被視為單獨的字段。
為了解決這個問題,我們添加了一個延遲:
<TextBox Text="{Binding CostOut, StringFormat='{}{0:C}', Delay=1000 />
效果更好,因為大多數人在格式化數字之前已經完成了鍵入操作。 但是,該應用程序很復雜,並且處理重要的財務數據,有些用戶在鍵入數字時會仔細考慮。 對於這些慢速打字機,這種延遲仍然導致他們的輸入重新格式化為中型。
我不願意進一步走“延遲”路線,因為我們最終會到達在有人保存之前不進行格式化的地步。 我發現並嘗試了WPF CurrencyTextBox,但由於“收銀機”樣式的鍵入過於陌生,因此被拒絕作為解決方案。
當前,提出的解決方案是從應用程序中刪除所有格式,並且僅在保存時格式化。 這對我來說太劇烈了,我不禁想知道是否有更好的解決方案?
您可以嘗試在textBox失去焦點時將其設置為所需的格式,而將焦點放在LostFocus
事件上。 它允許用戶輸入所需的時間,不會像在“保存”按鈕上設置格式時那樣劇烈。
如評論中所述,我創建了一個小示例,說明如何在您的ViewModel中將LostFocus事件綁定到ICommand
屬性。
附加屬性如下所示:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace TextBoxLostFocusBehaviorExample
{
internal static class TextBoxExtensions
{
public static readonly DependencyProperty LostFocusCommandProperty = DependencyProperty.RegisterAttached(
"LostFocusCommand",
typeof(ICommand),
typeof(TextBoxExtensions),
new PropertyMetadata(default(ICommand), OnLostFocusCommandChanged));
private static void OnLostFocusCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TextBox textBox = d as TextBox;
if (textBox == null)
{
return;
}
if (e.NewValue != null)
{
textBox.LostFocus += TextBoxOnLostFocus;
}
}
private static void TextBoxOnLostFocus(object sender, RoutedEventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox == null)
{
return;
}
ICommand command = GetLostFocusCommand(textBox);
command.Execute(null);
}
public static void SetLostFocusCommand(DependencyObject element, ICommand value)
{
element.SetValue(LostFocusCommandProperty, value);
}
public static ICommand GetLostFocusCommand(DependencyObject element)
{
return (ICommand)element.GetValue(LostFocusCommandProperty);
}
}
}
然后,在ViewModel中,您將擁有ICommand
類型的屬性,該屬性如下所示:
private ICommand lostFocusCommand;
public ICommand LostFocusCommand
{
get { return lostFocusCommand ?? (lostFocusCommand = new RelayCommand(p => CostOutLostFocus())); }
}
當觸發LostFocus
CostOutLostFocus
時,將調用CostOutLostFocus
。
視圖中附加屬性的用法如下所示:
<TextBox Text="{Binding CostOut, Mode=TwoWay}" TextBoxLostFocusBehaviorExample:TextBoxExtensions.LostFocusCommand="{Binding LostFocusCommand}"/>
TextBoxLostFocusBehaviorExample是定義附加屬性的class
的名稱空間。
當前,提出的解決方案是從應用程序中刪除所有格式,並且僅在保存時格式化。 這對我來說太劇烈了,我不禁想知道是否有更好的解決方案?
您可以通過簡單地將綁定的UpdateSourceTrigger屬性設置為XAML標記中的LostFocus的默認值,來更新source屬性並在用戶退出TextBox時應用格式設置:
<TextBox Text="{Binding CostOut, StringFormat={}{0:C}, UpdateSourceTrigger=LostFocus}" />
這至少比保存時應用格式更好。
另一種選擇是使用某種蒙版的TextBox。 沒有內置的內置組件,但是您可以嘗試使用開源擴展的WPF工具包中提供的內置組件: https : //wpftoolkit.codeplex.com/wikipage? title = MaskedTextBox&referringTitle =Home
還有一些商業選項可用: http : //docs.telerik.com/devtools/wpf/controls/radmaskedinput/features/maskedinput-controls/currency
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.