#1,096 – The RoutedUICommand Adds a Text Property

When creating a custom command object, you can use either a RoutedCommand or a RoutedUICommand object.  Using the RoutedUICommand object allows you to associate some text with the command, using its Text property.  This text is typically the text that you want the user to see in the user interface.

Below, we create a new command and set its text.

    public partial class MainWindow : Window
        public MainWindow()
            this.DataContext = this;

        public static RoutedCommand GreetUserCommand = new RoutedUICommand("Howdy!", "GreetUser", typeof(MainWindow));

        private void GreetUser_CanExecute(object sender, CanExecuteRoutedEventArgs e)
            e.CanExecute = true;

        private void GreetUser_Executed(object sender, ExecutedRoutedEventArgs e)
            MessageBox.Show("Howdy howdy I'm a cowboy");

        private void txtSomeText_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
            if (e.Command == ApplicationCommands.Paste)
                e.Handled = true;

In XAML, we reference the Text property for a button’s content. Note that we don’t need to specify text for the MenuItem–it will automatically get the text from the RoutedUICommand.

        <CommandBinding Command="{x:Static loc:MainWindow.GreetUserCommand}" CanExecute="GreetUser_CanExecute" Executed="GreetUser_Executed"/>

            <MenuItem Command="{x:Static loc:MainWindow.GreetUserCommand}"/>

        <TextBox Name="txtSomeText" CommandManager.PreviewExecuted="txtSomeText_PreviewExecuted" Width="220" Height="25" Margin="10"/>
        <Button HorizontalAlignment="Center" Padding="10,5" Margin="10" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}" Command="{x:Static loc:MainWindow.GreetUserCommand}"/>



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

3 Responses to #1,096 – The RoutedUICommand Adds a Text Property

  1. Pingback: Dew Drop – June 19, 2014 (#1800) | Morning Dew

  2. Shawn says:

    Your link for creating a custom command object is trying to bring me to the admin edit page.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: