我有一个带有一些文本框的Wpf应用程序,用于十进制输入。
当我按下PC键盘的数字键盘上的“点”键(。)时,我会发送正确的小数点分隔符。
例如,在意大利语中,小数点分隔符为“逗号”(,)...是否可以设置“点”键以在按下时发送“逗号”字符?
答案 0 :(得分:6)
虽然您可以按照Mamta Dalal的建议在WPF中设置默认转换器区域设置,但将“十进制”键按下转换为正确的字符串是不够的。此代码将在数据绑定控件上显示正确的货币符号和日期/时间格式
//Will set up correct string formats for data-bound controls,
// but will not replace numpad decimal key press
private void Application_Startup(object sender, StartupEventArgs e)
{
//Among other settings, this code may be used
CultureInfo ci = CultureInfo.CurrentUICulture;
try
{
//Override the default culture with something from app settings
ci = new CultureInfo([insert your preferred settings retrieval method here]);
}
catch { }
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
//Here is the important part for databinding default converters
FrameworkElement.LanguageProperty.OverrideMetadata(
typeof(FrameworkElement),
new FrameworkPropertyMetadata(
XmlLanguage.GetLanguage(ci.IetfLanguageTag)));
//Other initialization things
}
我发现在窗口范围内处理previewKeyDown事件比特定于文本框更清晰(如果可以在应用程序范围内应用它会更好)。
public partial class MainWindow : Window
{
public MainWindow()
{
//Among other code
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator != ".")
{
//Handler attach - will not be done if not needed
PreviewKeyDown += new KeyEventHandler(MainWindow_PreviewKeyDown);
}
}
void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Decimal)
{
e.Handled = true;
if (CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator.Length > 0)
{
Keyboard.FocusedElement.RaiseEvent(
new TextCompositionEventArgs(
InputManager.Current.PrimaryKeyboardDevice,
new TextComposition(InputManager.Current,
Keyboard.FocusedElement,
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
) { RoutedEvent = TextCompositionManager.TextInputEvent});
}
}
}
}
如果有人想出办法在整个应用程序范围内设置它......
答案 1 :(得分:5)
又快又脏:
private void NumericTextBox_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Decimal) {
var txb = sender as TextBox;
int caretPos=txb.CaretIndex;
txb.Text = txb.Text.Insert(txb.CaretIndex, System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);
txb.CaretIndex = caretPos + 1;
e.Handled = true;
}
}
答案 2 :(得分:3)