#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()
        {
            InitializeComponent();
            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.

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

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

    <StackPanel>
        <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}"/>
    </StackPanel>

1096-001

Advertisement