【发布时间】:2011-08-09 23:12:01
【问题描述】:
可能重复:
How do I get a TextBox to only accept numeric input in WPF?
我目前正在开发一个 WPF 应用程序,我希望在其中有一个只能包含数字条目的文本框(包括点和减号)。
我知道如何在 Windows 窗体中执行此操作,但 WPF 事件对我来说非常不同。
【问题讨论】:
可能重复:
How do I get a TextBox to only accept numeric input in WPF?
我目前正在开发一个 WPF 应用程序,我希望在其中有一个只能包含数字条目的文本框(包括点和减号)。
我知道如何在 Windows 窗体中执行此操作,但 WPF 事件对我来说非常不同。
【问题讨论】:
只需为 keydown 事件添加一个处理程序,并为您不想允许的键设置 e.handled=true。该示例在页面上并处理 alt-p 和 alt-n 但原理相同。您将需要修改此代码,因为它并非旨在取消击键,但它确实显示了如何处理 keydown 事件。
<Window x:Class="Gabe2a.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
DataContext="{Binding Source={x:Static Application.Current}}"
Title="Gabriel Main" Height="600" Width="800" KeyDown="Window_KeyDown">
private void Window_KeyDown(object sender, KeyEventArgs e)
{
// Debug.WriteLine("Main Window Window_KeyDown " + e.Key.ToString());
e.Handled = false;
if (e.KeyboardDevice.Modifiers == ModifierKeys.Alt) // && e.KeyboardDevice.IsKeyDown(Key.RightAlt))
{
if (e.Key == Key.System && e.SystemKey == Key.N)
{
e.Handled = true;
App.StaticGabeLib.Search.NextDoc();
}
else if (e.Key == Key.System && e.SystemKey == Key.P)
{
e.Handled = true;
App.StaticGabeLib.Search.PriorDoc();
}
}
base.OnKeyDown(e);
}
将 KeyDown 附加到文本框的示例
<TextBox KeyDown="TBKeydown" />
【讨论】: