Bind a button to a command (Windows Phone 7.5)

前端 未结 2 2057
暖寄归人
暖寄归人 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:26

    To add to Jays answer:

    My all time favorite is the DelegateCommand from the Patterns and Practices team @ Microsoft. Check out this post for more info.

    0 讨论(0)
  • 2021-02-05 16:29

    In your XAML:

    <Button Content="My Button" Command="{Binding MyViewModelCommand}" />
    

    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
                    }));
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题