WPF Commands Tutorial Part 2

This is episode 2 of working with WPF commands. In this we will cover implementing a Relay/Delegate Command handling class to create multiple commands without the need for individual classes. We also learn how to enable and disable our WPF commands by utilizing the provided events in the ICommand interface.

We make a simple application that displays pre-determined messages in either a MessageBox or a Console.WriteLine().

Don’t forget the survey below to let me know your thoughts

—Code from this episode below—

MainWindow.xaml (With Bindings)

<Grid>
     <StackPanel Width="250">
         <TextBlock>Messages</TextBlock>
         <ListView Height="200" x:Name="comboMessages" ItemsSource="{Binding MyMessages}"/>
         <Button Command="{Binding MessageBoxCommand}" CommandParameter="{Binding ElementName=comboMessages, Path=SelectedItem}">
             Message Box
         </Button>
         <Button Command="{Binding ConsoleLogCommand}" CommandParameter="{Binding ElementName=comboMessages, Path=SelectedItem}">
             Console Log
         </Button>
     </StackPanel>
</Grid>

RelayCommand.cs

public class RelayCommand : ICommand
{
   readonly Action<object> _execute;
   readonly Predicate<object> _canExecute;
 
   public RelayCommand(Action<object> execute, Predicate<object> canExecute)
   {
       if (execute == null)
           throw new NullReferenceException("execute");
 
       _execute = execute;
       _canExecute = canExecute;
   }
 
   public RelayCommand(Action<object> execute) : this(execute, null)
   {
 
   }
 
   public event EventHandler CanExecuteChanged
   {
       add { CommandManager.RequerySuggested += value; }
       remove { CommandManager.RequerySuggested -= value; }
   }
 
   public bool CanExecute(object parameter)
   {
       return _canExecute == null ? true : _canExecute(parameter);
   }
 
   public void Execute(object parameter)
   {
       _execute.Invoke(parameter);
   }
}

 

MessageViewModel.cs

public class MessageViewModel
{
    public ObservableCollection<string> MyMessages { get; private set; }
 
    public RelayCommand MessageBoxCommand { get; private set; }
    public RelayCommand ConsoleLogCommand { get; private set; }
 
    public MessageViewModel()
    {
        MyMessages = new ObservableCollection<string>()
        {
            "Hello World!",
            "My name is Joe",
            "I love learning commands",
            "Im a message box!",
            "Im a console!"
        };
 
        MessageBoxCommand = new RelayCommand(DisplayInMessageBox);
        ConsoleLogCommand = new RelayCommand(DisplayInConsole, ConsoleCanUse);
    }
 
    public void DisplayInMessageBox(object message)
    {
        MessageBox.Show((string)message);
    }
 
    public void DisplayInConsole(object message)
    {
        Console.WriteLine((string)message);
    }
 
    public bool MessageBoxCanUse(object message)
    {
        if ((string)message == "Im a console!")
            return false;
 
        return true;
    }
 
    public bool ConsoleCanUse(object message)
    {
        if ((string)message == "Im a message box!")
            return false;
 
        return true;
    }
}

4 thoughts on “WPF Commands Tutorial Part 2

  1. Hi, could you please share some advise for using RelayCommand with Async/Await for asynchronous call to DB(via ado.net/ef/dapper egc.) or to WEB service!?

    Thanks in advance

      1. Thanks for the quick reply!

        I appreciate this, but my tough was to “push” you to write such a good tutorial, howto do this, because your previous are awesome and very helpful!
        🙂

        1. Being a student myself and having much to learn as well, I avoid making tutorials on things I’m not completely “in touch” with. Though, it does sound like an interesting tutorial. I will put it on a list of things to do more research on. I try to make my videos more than, “Here is code, copy & paste it”. To meet that standard I don’t want to simply show “how” to do it, but also be able to explain it at a simple intuitive level(Or so I try). Often in programming we(At least I have at times) just memorize how to do things and then regurgitate them when needed. Rather than fully comprehending every inch of it. My over-explanation aside – I will try to meet that standard I set for myself so I can create a video on it. Thanks for your interest in reaching out! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *