views:

366

answers:

1

I have created WPF MVVM application, and set WPFToolkit DataGrid binding to DataTable so I want to know how to implement DataTable property to notify changed. Currently my code is like below.

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

Is it has another solution for this problem?

A: 

Hi Ekkapop,

There are 2 ways your Table data could change: Either an element could be added/removed from the collection, or some properties from within an element could change.

The first scenario is easy to handle: make your collection an ObservableCollection<T>. Invoking .Add(T item) or .Remove(item) on your table will fire a change notification through to the View for you (and the table will update accordingly)

The second scenario is where you need your T object to implement INotifyPropertyChanged...

Ultimately your code should look something like this:

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

Now set the datacontext of your View to be an instance of your ViewModel, and bind to the collection, like:

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

Hope this helps :) Ian

IanR