5

私は MVVM を初めて使用します。最近、MVVM パターンに従って最初のプロジェクトを開始しました。IDataErrorInfo インターフェイスを使用して ObservableCollection を検証しようとすると問題が発生します。私の ObservableCollection は次のようになります。

ObservableCollection<Magazine> magazineRepository;
    public ObservableCollection<Magazine> MagazineRepository
    {
        get { return magazineRepository; }
        set
        {
            if (value != null)
            {
                bladRepository = value;
                OnPropertyChanged("MagazineRepository");
            }
        }
    }

そして、私のXAMLは次のようになります:

<ListBox x:Name="listMagazineRepository"
                 Grid.ColumnSpan="2"
                 ItemsSource="{Binding}" 
                 DataContext="{Binding MagazineRepository}"
                 DisplayMemberPath="Navn" 
                 SelectedItem="{Binding Path=SelectedItem}"/>

        <TextBox x:Name="txtName" Grid.Row="1" Grid.Column="0"
                    Text="{Binding ElementName=listMagazineRepository, Path=SelectedItem.Navn, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
        <TextBox x:Name="txtPrice" Grid.Row="2" Grid.Column="0"
                    Text="{Binding ElementName=listMagazineRepository, Path=SelectedItem.Pris, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

オブジェクトを含む単純な listBox です。アイテムを選択すると、選択したオブジェクトのプロパティがテキスト ボックスに表示され、リストボックス オブジェクトにバインドされます。

私の問題は、このようにコードを設定した場合、データを検証する方法を理解できる唯一の方法はドメイン モデルにあるということです。これは実際には良い方法ではありません。ViewModel で検証したいと思います。それがそこに着く前に。基本的に、ViewModel の MagazineRepository の各プロパティを検証したいのですが、どうすればこれを行うことができますか?

PS: この掲示板 (および一般的なプログラミング掲示板) に投稿するのは初めてなので、質問に情報が不足している場合はお知らせください。必要な詳細を提供します。

どうもありがとう。

4

2 に答える 2

3

まず、Dtex が言うように、Magazine クラスではなく MagazineViewModel クラスを使用する必要があります。例えば

public class MagazineViewModel : INotifyPropertyChanged, IDataErrorInfo
{
  private string navn;
  private string pris;
  private string error;

  public string Navn
  {
    get { return navn; }
    set
    {
      if (navn != value)
      {
        navn = value;
        RaisePropertyChanged("Navn");
      }
    }
  }
  public string Pris
  {
    get { return pris; }
    set
    {
      if (pris != value)
      {
        pris = value;
        RaisePropertyChanged("Pris");
      }
    }
  }
  public string Error
  {
    get { return error; }
    set
    {
      if (error != value)
      {
        error = value;
        RaisePropertyChanged("Error");
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  public string this[string columnName]
  {
    get
    {
      var result = string.Empty;

      switch (columnName)
      {
        case "Pris":
          if (string.IsNullOrWhiteSpace(Pris))
          {
            result =  "Pris is required";
          }
          break;
        case "Navn":
          if (string.IsNullOrWhiteSpace(Navn))
          {
           result =  "Navn is required";
          }
          break;
      }

      return result;

    }
  }

  private void RaisePropertyChanged(string PropertyName)
  {
    var e = PropertyChanged;
    if (e != null)
    {
      e(this, new PropertyChangedEventArgs(PropertyName));
    }
  }

}

注意すべき重要なプロパティは、「public string this[string columnName]」です。ColumnName はバインドされたプロパティの 1 つになり、ここで検証を行うことができます。

次に考慮すべきことは、あなたの MainViewModel (あなたの DataContext) です。例えば

public class MainViewModel : INotifyPropertyChanged
{
  //Use a readonly observable collection. If you need to reset it use the .Clear() method
  private readonly ObservableCollection<MagazineViewModel> magazines = new ObservableCollection<MagazineViewModel>();

  private MagazineViewModel selectedItem;

  //Keep the item being edited separate to the selected item
  private MagazineViewModel itemToEdit;

  public ObservableCollection<MagazineViewModel> Magazines { get { return magazines; } }
  public MagazineViewModel SelectedItem
  {
    get { return selectedItem; }
    set
    {
      if (selectedItem != value)
      {
        selectedItem = value;
        RaisePropertyChanged("SelectedItem");
        //When the selected item changes. Copy it to the ItemToEdit
        //This keeps the the copy you are editing separate meaning that invalid data isn't committed back to your original view model
        //You will have to copy the changes back to your original view model at some stage)
        ItemToEdit = Copy(SelectedItem);
      }
    }
  }
  public MagazineViewModel ItemToEdit
  {
    get { return itemToEdit; }
    set
    {
      if (itemToEdit != value)
      {
        itemToEdit = value;
        RaisePropertyChanged("ItemToEdit");
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  public MainViewModel()
  {
    //Ctor...
  }

  //Create a copy of a MagazineViewModel
  private MagazineViewModel Copy(MagazineViewModel ToCopy)
  {
    var vm = new MagazineViewModel();
    vm.Navn = ToCopy.Navn;
    vm.Pris = ToCopy.Pris;
    return vm;
  }

  private void RaisePropertyChanged(string PropertyName)
  {
    //...
  }
}

ここで欠けているのは、変更を元のビュー モデルにコピーする方法だけです。選択した項目が変更される前 (ItemToEdit が有効な場合) に実行するか、ItemToEdit が有効な場合にのみ有効になる [コミット] ボタンを使用できます。元のビュー モデルが無効な状態になることを許可できる場合は、コピーについて心配する必要はありません。

最後に XAML

エラー ツールチップを表示する暗黙のスタイル

<Style
  TargetType="{x:Type TextBox}">
  <Setter
    Property="ToolTip"
    Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Style>

コントロールとバインディング

<ListBox
  ItemsSource="{Binding Magazines}"
  DisplayMemberPath="Navn"
  SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay}" />
<TextBox
  Margin="5"
  x:Name="txtName"
  Grid.Row="1"
  Grid.Column="0"
  Text="{Binding ItemToEdit.Navn, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<TextBox
  Margin="5"
  x:Name="txtPrice"
  Grid.Row="2"
  Grid.Column="0"
  Text="{Binding ItemToEdit.Pris, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />

TextBoxes は ItemToEdit にバインドします。ItemToEdit は、SelectedItem の同期コピーになります。

于 2013-07-29T12:16:38.790 に答える
3

If i understand correctly you want to validate the Magazine object. If that's the case, one way to do it is to wrap that class in a viewmodel, let's call it MagazineVM, that implements IDataErrorInfo and keep the magazine object updated. You then bind to the view a list of MagazineVM. As a very simple example:

public class MagazineVM : IDataErrorInfo, INotifyPropertyChanged
{
   private Magazine _magazine;

   public int FirstMagazineProperty
   {
      get { return _magazine.FirstMagazineProperty; }
      set { _magazine.FirstMagazineProperty = value; RaisePropertyChanged("FirstMagazineProperty"); }
   }

   //INotifyPropertyChanged implementation

   //IDataErrorInfo implementation
}
于 2012-11-13T10:37:15.920 に答える