Pages

Sunday, September 7, 2014

WPF Save command

What can be easier then type

In WPF it is a designed way to interact with user. It is much simpler then binding to events as it gives you a better flexibility with CanExecute property and you code becomes reusable.

I wanted to implement that command and checked google. I was surprised to find that there were not any direct explanation in first 2-3 results. Even more, MSDN has a really bad explanation of what that command is and as an example there is a source code for Paste command. I am not sure why :)

So just in case - if you want to bind Save command you can CommandBinding to your own handlers like this:

XAML

    
        
        
    
    
        
        
    


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

        private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true; //your logic
        }

        private void SaveCommand_OnExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Save!");
        }

        private void OpenCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }

        private void OpenCommand_OnExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Open");
        }
    }