01 September 2010

Tip #1 MVVM Delegate Command with an ObservableCollection

First of all I get the DelegateCommand from the .toolbox courses (I encourage you to download them and find it).

Using this DelegateCommand wich we bind to a button Command for instance (I always add CommandParameter in xaml too, (in order to work fine).

Now my layoutroot datacontext viewmodel has the following property:

private ObservableCollection _sales;
public ObservableCollection Sales
{
  get { return _sales; }
  set
      {
         _sales= value;
         NotifyPropertyChanged("Sales");
         }
        }


And now (in this case is a WPF application, in case you use SL I recommend you to use PagedViewCollection), I instance the command in the constructor:


PaidCommand = new DelegateCommand()
{
 ExecuteCommand = () =>
   {
      bw = new BackgroundWorker();
      bw.RunWorkerCompleted += (s, e) =>
        {
          NotifyPropertyChanged("Sales"); //#1
        };
      bw.DoWork += (s1, e1) =>
        {
           _sales= DM.GetSales(_date1, _date2); //#2
        };
      bw.RunWorkerAsync();
    }

};

 In #2 we process every lines of code we want filling our private fields and when it's finished we publish
simply Notifying them #1 (In my case I have a datagrid with ItemsSource = {Binding Sales})

I hope it helps you (I like this way to do).


And now just a question if any one knows , for other classes I would like to define. Let's suppose a not MVVM environment

Button1.OnClick += (s,e) =>
{
 ...
};

Do you know a way to remove inside the ... the previous delegates like the old way:


Button1.OnClick -= OnButton1Clicked;

No comments: