【发布时间】:2011-10-29 19:42:40
【问题描述】:
我为 WPF 文本框编写了一个名为“IsValid”的小附加属性,如下所示:
public enum InputTypes
{
Any,
Integer,
Double,
Float
}
/// <summary>
/// This attached property can be used to validate input for <see cref="TextBox"/>.
/// </summary>
public class IsValid : DependencyObject
{
public static readonly DependencyProperty InputProperty = DependencyProperty.Register(
"Input",
typeof(InputTypes),
typeof(IsValid),
new UIPropertyMetadata(InputTypes.Any, onInput));
public static InputTypes GetInput(DependencyObject d)
{
return (InputTypes)d.GetValue(InputProperty);
}
public static void SetInput(DependencyObject d, InputTypes value)
{
d.SetValue(InputProperty, value);
}
private static void onInput(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = (TextBox)d;
var value = (InputTypes)e.NewValue;
switch (value)
{
case InputTypes.Any:
textBox.PreviewTextInput -= validateInput;
textBox.PreviewKeyDown -= validateKeyDown;
break;
default:
textBox.PreviewTextInput += validateInput;
textBox.PreviewKeyDown += validateKeyDown;
break;
}
}
private static void validateInput(object sender, TextCompositionEventArgs e)
{
// enforce numeric input when configured ...
var textBox = (TextBox) sender;
var inputTypes = (InputTypes) textBox.GetValue(InputProperty);
foreach (var c in e.Text)
{
switch (inputTypes)
{
case InputTypes.Integer:
if (!char.IsDigit(c))
{
e.Handled = true;
return;
}
break;
case InputTypes.Double:
case InputTypes.Float:
if (!char.IsNumber(c))
{
e.Handled = true;
return;
}
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private static void validateKeyDown(object sender, KeyEventArgs e)
{
// block [SPACE] when numeric input is expected ...
var textBox = (TextBox)sender;
var inputTypes = (InputTypes)textBox.GetValue(InputProperty);
if (inputTypes != InputTypes.Any && e.Key == Key.Space)
e.Handled = true;
}
}
以下是我的使用方法:
<Window x:Class="Spike.Wpf.Controls.TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:values="clr-namespace:Spike.Wpf.Controls.Input;assembly=Spike.Wpf.Controls"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox values:IsValid.Input="Double" />
</Grid>
在初始化(DependencyProperty)之后,IsValid 中的任何方法都不会被调用。我错过了什么?
【问题讨论】:
-
您能否验证该属性被分配给
InputTypes.Double而不是字符串"Double"? -
我会再看看您对输入的处理。我不认为你的支票在做你认为的那样。 stackoverflow.com/questions/228532/…
-
@Rachel:是的,已经解决了这个问题(见答案),我可以非常肯定我确实得到了预期的价值。 WPF 负责解析。 @Brent:的确,你是绝对正确的。我也意识到我的解决方案是不够的。仅仅指定“double”或“integer”是不够的。我还需要指定允许的小数位数以及通常的最小值和最大值。所以,我决定继续构建几个
MarkupExtension类。生成的语法非常令人愉快。我对 WPF 很陌生,但到目前为止我不得不说它非常强大......
标签: c# wpf xaml attached-properties