【发布时间】:2017-06-21 05:19:00
【问题描述】:
在通用 Windows 应用程序应用程序中设置 MVVM Light 后,我有以下结构,我想知道在 2017 年使用 UWP 和 mvvmlight 来通知用户错误并可能重置文本框的最干净的方法是什么需要时的价值。唯一的技巧是文本框是 UserControl 的一部分(为了清楚起见,清理了不必要的 xaml 代码),因为它将被多次使用。我还添加了 DataAnnotations 和 ValidationResult 以进行演示,而不是暗示这是最好的方法或到目前为止它正在以任何方式工作。
代码在绑定以及添加和删除值方面工作正常
-
视图模型
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 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> -
后面的用户控制代码:
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)); }
【问题讨论】:
标签: c# xaml mvvm win-universal-app mvvm-light