在使用MVVM的Windows商店App中,我有一个带双向绑定的TextBox,它只允许数值。当按下非数字键时,使用MVVM简单地忽略的正确程序是什么?
仅当文本框失去焦点时,才会触发INotifyPropertyChanged更改的值。我基本上想要对我的属性进行即时验证。我找不到一个恰当的简单例子。
答案 0 :(得分:2)
为什么不创建附加属性来包含此行为?像这样:
public class TextBoxHelper
{
public static bool GetRestrictToNumerical(DependencyObject obj)
{
return (bool)obj.GetValue(RestrictToNumericalProperty);
}
public static void SetRestrictToNumerical(DependencyObject obj, bool value)
{
obj.SetValue(RestrictToNumericalProperty, value);
}
public static readonly DependencyProperty RestrictToNumericalProperty =
DependencyProperty.RegisterAttached("RestrictToNumerical", typeof(bool), typeof(TextBoxHelper), new PropertyMetadata(false, onRestrictToNumericalChanged));
private static void onRestrictToNumericalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var tb = d as TextBox;
if (tb == null)
return;
if ((bool)e.NewValue)
tb.KeyDown += tb_KeyDown;
else
tb.KeyDown -= tb_KeyDown;
}
static void tb_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
{
e.Handled = e.Key < VirtualKey.Number0 || e.Key > VirtualKey.Number9;
}
}
您可以在XAML中使用它,如下所示:
<Page
x:Class="App4.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App4"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBox VerticalAlignment="Center" local:TextBoxHelper.RestrictToNumerical="True" InputScope="Number" />
</Grid>
</Page>
This是一种干净的MVVM方法,可用于您可能需要执行的所有输入验证。对于你的简单问题,它可能有点过分,但它对于更复杂的验证很有用。