1

相互に依存する 2 つのプロパティを検証するための推奨されるアプローチは何ですか?

古典的な例では、開始日は終了日よりも前でなければなりません:

  1. ユーザーは開始「6th」を入力します
  2. ユーザーが最後に「3rd」と入力 - 両方のフィールドを無効としてマークする必要があります
  3. ユーザーが開始を「1st」に修正 - 両方のフィールドで問題ないはずです

ReactiveValidatedObject はここでどのように役立つでしょうか?

できれば、WPF と Silverlight で動作するソリューションが必要です。

4

1 に答える 1

2

WPF アプリに MVVM パターンを使用している場合は、非常に簡単です。View が検証を行う代わりに、ViewModel が検証を行います。ビューは、ViewModel が公開するものを表示するダム レイヤーにすぎません。すべての UI 検証は、テスト可能にするために、ViewModel によって実行する必要があります。

私のViewModelは次のようになります。

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;
    }
}

そして、ViewをこのViewModelにデータバインドします->

        <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>
于 2011-05-26T15:48:22.333 に答える