Bind a button to a command (Windows Phone 7.5)

前端 未结 2 2058
暖寄归人
暖寄归人 2021-02-05 16:09

I\'m working on my windows-phone app which uses some simple data binding. I\'ve already created a app which was based on the MvvM programming method.The app i\'m currently worki

2条回答
  •  一向
    一向 (楼主)
    2021-02-05 16:29

    In your XAML:

    In your view-model:

    public class MyViewModel
    {
    
        public MyViewModel()
        {
            MyViewModelCommand = new ActionCommand(DoSomething);
        }
    
        public ICommand MyViewModelCommand { get; private set; }
    
        private void DoSomething()
        {
            // no, seriously, do something here
        }
    }
    

    INotifyPropertyChanged and other view-model pleasantries elided.
    An alternative way to structure the command in your view-model is shown at the bottom of this answer.

    Now, you'll need an implementation of ICommand. I suggest starting with something simple like this, and extend or implement other features/commands as necessary:

    public class ActionCommand : ICommand
    {
        private readonly Action _action;
    
        public ActionCommand(Action action)
        {
            _action = action;
        }
    
        public void Execute(object parameter)
        {
            _action();
        }
    
        public bool CanExecute(object parameter)
        {
            return true;
        }
    
        public event EventHandler CanExecuteChanged;
    }
    

    Here is an alternative way to layout your view-model:

    public class MyViewModel
    {
        private ICommand _myViewModelCommand;
        public ICommand MyViewModelCommand
        {
            get 
            {
                return _myViewModelCommand
                    ?? (_myViewModelCommand = new ActionCommand(() => 
                    {
                        // your code here
                    }));
            }
        }
    }
    

提交回复
热议问题