Tuesday, February 4, 2014

Async Command Call in WPF MVVM


Something Like below. this is straightforward, and I am not going to explain in details:


    public class MainWindowViewModel:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public ICommand AddCommand { get; set; }
        private ObservableCollection < Trade> trades=new ObservableCollection < Trade>();
        public ObservableCollection < Trade> Trades
        {
            get { return this.trades; }
            set
            {
                this.trades = value;
                NotifyPropertyChanged("Trades");
            }
        }
        public MainWindowViewModel()
        {
            this.AddCommand=new AsynAddCommand(this);
        }
        public bool CanAdd()
        {
            return true;
        }
        public async Task Add()
        {
            for (int i = 1; i <=10; i++)
            {
                Trades.Add(await  NewTrade(i));
            }
        }
        public async Task < Trade> NewTrade(int i)
        {
            await Task.Delay(1000);
            return new Trade() {TradeId = i.ToString(), Price = 100*i, Volume = 20*i};
        }
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                this.PropertyChanged(this,new PropertyChangedEventArgs(info));
            }
        }
    }
    public class AsynAddCommand : ICommand
    {
        private MainWindowViewModel _vm;
        public AsynAddCommand(MainWindowViewModel vm)
        {
            _vm = vm;
        }
        public bool CanExecute(object parameter)
        {
            return _vm.CanAdd();
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public async void Execute(object parameter)
        {
            _vm.Add();
        }
    }

1 comment:

Unknown said...

Hi Jie,

Sr. C#/.Net Developers - REMOTE JOB

My client with national & international presence is seeking for above consultants
I would like to have a 15 mins call to talk about your needs & if there would be any opportunities to work together.

Regards,
Sumit@sans[dot]com