我在 UWPx:Bind
和数据验证方面有点挣扎。我有一个非常简单的用例:我希望用户输入int
一个TextBox
TextBlock
在用户离开后立即在 a 中显示数字TextBox
。我可以InputScope="Number"
为设置TextBox
,但这并不能阻止使用键盘键入的人键入 alpha 字符(或粘贴某些内容)。问题是,当我用 绑定一个字段时,如果您绑定的字段被声明为 ,您Mode=TwoWay
似乎无法阻止 a 。如果输入是数字,我想检查该方法,但在此之前发生异常。我的(非常简单的)ViewModel(这里没有模型,我尽量让它尽可能简单):System.ArgumentException
int
set
public class MyViewModel : INotifyPropertyChanged
{
private int _MyFieldToValidate;
public int MyFieldToValidate
{
get { return _MyFieldToValidate; }
set
{
this.Set(ref this._MyFieldToValidate, value);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisedPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
else
{
storage = value;
this.RaisedPropertyChanged(propertyName);
return true;
}
}
}
我背后的代码:
public sealed partial class MainPage : Page
{
public MyViewModel ViewModel { get; set; } = new MyViewModel() { MyFieldToValidate = 0 };
public MainPage()
{
this.InitializeComponent();
}
}
还有我的整个 XAML:
<Page
x:Class="SimpleFieldValidation.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:SimpleFieldValidation"
xmlns:vm="using:SimpleFieldValidation.ViewModel"
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}">
<Grid.RowDefinitions>
<RowDefinition Height="10*" />
<RowDefinition Height="*" />
<RowDefinition Height="10*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Row="1" Grid.Column="0" Text="{x:Bind ViewModel.MyFieldToValidate, Mode=TwoWay}" x:Name="inputText" InputScope="Number" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{x:Bind ViewModel.MyFieldToValidate, Mode=OneWay}" x:Name="textToDisplay" />
</Grid>
</Page>
如果我在 中输入数字字符TextBox
,一切正常。但是如果我输入一个非数字值(比如“d”)(它甚至没有到达set
for 方法第一个括号的断点MyFieldToValidate
):
是否有最佳实践来做我想做的事?最简单的解决方案是首先阻止用户输入除数字以外的其他字符,但我一直在寻找几个小时而没有找到简单的方法......另一个解决方案是在离开字段时验证数据,但我没有找到与 UWP 相关的东西,并且x:Bind
(WPF 的想法很少,但它们不能用 UWP 复制)。谢谢!