首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在WPF和SL中验证取决于属性

在WPF和SL中验证取决于属性
EN

Stack Overflow用户
提问于 2011-05-05 10:13:15
回答 1查看 320关注 0票数 1

根据一个属性验证两个属性的推荐方法是什么?

典型的例子是开始日期应该低于结束日期:

  1. 用户输入开始“6”
  2. 用户输入结束“第3”-这两个字段都应标记为无效的
  3. 用户更正为“1”,两个字段都应该是ok

ReactiveValidatedObject在这里有什么帮助呢?

我最好需要一个在WPF和Silverlight中工作的解决方案。

EN

回答 1

Stack Overflow用户

发布于 2011-05-26 15:48:22

如果您正在使用MVVM模式的WPF应用程序,它将是相当直接的。而不是由视图执行验证,而是由ViewModel来完成。视图应该只是一个哑巴层,显示ViewModel公开的内容。所有的UI验证都应该由ViewModel完成,这样它们才是可测试的。

我的ViewModel可能是这样的:

代码语言:javascript
复制
class MyViewModel : INotifyPropertyChanged
{
    /* declare ProperChanged event and implement  OnPropertyChanged() method */

    private DateTime _firstDate;
    public DateTime FirstDate
    {
        get { return _firstDate; }
        set
        {
            if (!AreDatesValid(value, _secondDate))
            {
                ErrorMessage = "Incorrect First Date";
                return;
            }
            _firstDate = value;
            OnPropertyChanged("FirstDate");
        }
    }

    private DateTime _secondDate;
    public DateTime SecondDate
    {
        get { return _secondDate; }
        set
        {
            if (!AreDatesValid(_firstDate, value))
            {
                ErrorMessage = "Incorrect Second Date";
                return;
            }
            _secondDate = value;
            OnPropertyChanged("SecondDate");
        }
    }

    private string _errorMessage;
    public string ErrorMessage
    {
        get { return _errorMessage; }
        set
        {
            _errorMessage = value;
            OnPropertyChanged("ErrorMessage");
        }
    }

    private bool AreDatesValid(DateTime firstDate, DateTime secondDate)
    {
        if(firstDate <= secondDate )
            return true;
        return false;
    }
}

然后对这个ViewModel ->进行数据库视图

代码语言:javascript
复制
        <DataTemplate DataType="{x:Type ViewModel:MyViewModel}">
           <Grid>
               <TextBox Text="{Binding Path=FirstDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
               <TextBox Text="{Binding Path=SecondDate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
               <TextBlock Text="{Binding Path=ErrorMessage}" />
           </Grid>
        <DataTemplate>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5896027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档