Create Key binding in WPF

后端 未结 5 1888
滥情空心
滥情空心 2020-11-30 08:47

I need to create input binding for Window.

public class MainWindow : Window
{
    public MainWindow()
    {
        SomeCommand = ??? () => OnAction();
           


        
5条回答
  •  情书的邮戳
    2020-11-30 09:13

    For your case best way used MVVM pattern

    XAML:

    
        
            
        
    
    

    Code behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    

    In your view-model:

    public class MyViewModel
    {
        private ICommand someCommand;
        public ICommand SomeCommand
        {
            get
            {
                return someCommand 
                    ?? (someCommand = new ActionCommand(() =>
                    {
                        MessageBox.Show("SomeCommand");
                    }));
            }
        }
    }
    

    Then you'll need an implementation of ICommand. This simple helpful class.

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

提交回复
热议问题