我寫了一個小的附加屬性叫做「的IsValid」爲WPF文本框,就像這樣:這裏無法獲得的DependencyProperty工作
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'而不是字符串'「雙師型」'? – Rachel
我會再看看你對輸入的處理。我不認爲你的支票正在做你認爲他們的。 http://stackoverflow.com/questions/228532/difference-between-char-isdigit-and-char-isnumber-in-c –
@Rachel:是的,解決了這個問題(看到答案)我可以非常認真的獲得預期的價值。 WPF負責解析。 @Brent:的確,你是對的。我也意識到我的解決方案是不夠的。只需指定「double」或「integer」是不夠的。我還需要指定允許的小數位數以及通常的最小值和最大值。所以,我決定繼續並建立幾個'MarkupExtension'類。由此產生的語法非常愉快。我對WPF很新,但到目前爲止,我不得不說它非常強大... –