1

WPF MVVM アプリケーションを作成し、WPFToolkit DataGrid バインディングを DataTable に設定したので、DataTable プロパティを実装して変更を通知する方法を知りたいです。現在、私のコードは以下のようなものです。

public DataTable Test
{
    get { return this.testTable; }
    set 
    { 
        ...
        ...
        base.OnPropertyChanged("Test");
    }
}

public void X()
{
    this.Test.Add(...); // I suppose this line will call to getter first (this.Test = get Test) and then it will call add letter, this mean that setter scope will never fire.
    base.OnPropertyChanged("Test"); // my solution is here :) but I hope it has better ways.
}

この問題の別の解決策はありますか?

4

1 に答える 1

1

テーブル データが変更される可能性のある方法は 2 つあります。要素がコレクションに追加/コレクションから削除されるか、要素内の一部のプロパティが変更される可能性があります。

最初のシナリオは簡単に処理できます。コレクションをObservableCollection<T>. .Add(T item)テーブルでorを呼び出す.Remove(item)と、ビューに変更通知が送信されます (それに応じてテーブルが更新されます)。

2 番目のシナリオは、T オブジェクトに INotifyPropertyChanged を実装する必要がある場合です...

最終的に、コードは次のようになります。

    public class MyViewModel
    {
       public ObservableCollection<MyObject> MyData { get; set; }
    }

    public class MyObject : INotifyPropertyChanged
    {
       public MyObject()
       {
       }

       private string _status;
       public string Status
       {
         get { return _status; }
         set
         {
           if (_status != value)
           {
             _status = value;
             RaisePropertyChanged("Status"); // Pass the name of the changed Property here
           }
         }
       }

       public event PropertyChangedEventHandler PropertyChanged;

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

View の datacontext を ViewModel のインスタンスに設定し、次のようにコレクションにバインドします。

<tk:DataGrid 
    ItemsSource="{Binding Path=MyData}"
    ... />

これが役立つことを願っています:)イアン

于 2009-10-17T06:39:59.410 に答える