在为通用Windows应用程序应用程序设置MVVM Light后,我有以下结构,并且想知道使用UWP和MvvmLight进行验证的最简洁方法,以便在需要时通知用户出现错误并可能重置文本框值。唯一的诀窍是Textbox是UserControl的一部分(为了清晰起见清理了不必要的XAML代码),因为它将被多次使用。同时,我添加了DataAnnotations和ValidationResult仅供演示,并不意味着这是最佳实践或迄今为止工作。
就绑定和添加/删除值而言,该代码运行良好
ViewModel
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Views;
using System;
using System.ComponentModel.DataAnnotations;
public class ValidationTestViewModel : ViewModelBase
{
private int _age;
[Required(ErrorMessage = "Age is required")]
[Range(1, 100, ErrorMessage = "Age should be between 1 to 100")]
[CustomValidation(typeof(int), "ValidateAge")]
public int Age
{
get { return _age; }
set
{
if ((value > 1) && (value =< 100))
_age= value;
}
}
public static ValidationResult ValidateAge(object value, ValidationContext validationContext)
{
return null;
}
}
查看
<Page
x:Class="ValidationTest.Views.ValidationTestPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ValidationTest.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding ValidationTestPageInstance, Source={StaticResource Locator}}"
xmlns:views="using:ValidationTest.Views">
<views:NumberEdit TextInControl="{Binding Age, Mode=TwoWay}" />
</Page>
UserControl
<UserControl
x:Class="ValidationTest.Views.Number"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ValidationTest.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="userControl1">
<Grid>
<TextBox x:Name="content" Text="{Binding TextInControl, ElementName=userControl1, Mode=TwoWay}"></TextBox>
</Grid>
</UserControl>
UserControl 代码后台:
public partial class NumberEdit : UserControl
{
public string TextInControl
{
get { return (string)GetValue(TextInControlProperty); }
set {
SetValue(TextInControlProperty, value);
}
}
public static readonly DependencyProperty TextInControlProperty =
DependencyProperty.Register("TextInControl", typeof(string),
typeof(NumberEdit), new PropertyMetadata(null));
}
DataContext
添加到页面或控件中,同时我已经更新了StringChanged
方法中的代码。 - Jayden