#1,089 – Adding a Parameter to a Command

When you set the Command property of a user interface element, you’re binding that element to a particular command.  The command, in turn, is associated with some code through its Executed property.

You can specify a command parameter using the CommandParameter property.  The data in this property will be passed to the code that runs when the command executes.

The XAML fragment below shows two buttons that both bind to the same command, but pass in different data.

        <Button Content="Open A"
                Command="ApplicationCommands.Open"
                CommandParameter="File A"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />
        <Button Content="Open B"
                Command="ApplicationCommands.Open"
                CommandParameter="File B"
                Margin="10" Padding="10,3"
                HorizontalAlignment="Center" />

We can then read that parameter in the code bound to the command’s Executed property.

        public void Executed_Open(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show(string.Format("Executing Open command for [{0}]", e.Parameter));
        }

1089-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #1,089 – Adding a Parameter to a Command

  1. Pingback: Dew Drop – June 9, 2014 (#1793) | Morning Dew

Leave a comment