views:

39

answers:

1

I am creating a command which will have a Textbox control as target.

Code to create the command:

public class Commands
{
    public static RoutedCommand Appender;

    static Commands()
    {
        Appender = new RoutedCommand();
    }

    public static void AppenderExecuted(object target, ExecutedRoutedEventArgs e)
    {
        System.Windows.Controls.TextBox targetTbox = target as System.Windows.Controls.TextBox;
        if (targetTbox != null)
        {
            targetTbox.Text += "AppendedText";
        }
    }
}

XAML:

<StackPanel Name="span" FocusManager.IsFocusScope="True">
    <Menu IsMainMenu="True">
        <MenuItem Header="Tools">
            <MenuItem Header="_Append" Name="menuAppend" />
        </MenuItem>
    </Menu>
    <TextBox Height="100"  Name="txtEdit"></TextBox>
</StackPanel>    

CS: Window constructor:

        //create bindings
        CommandBinding bindingTM = new CommandBinding(Commands.Appender, Commands.AppenderExecuted);

        //[THIS DOESN'T WORK]
        this.CommandBindings.Add(bindingTM);

        //[THIS WORKS]
        txtEdit.CommandBindings.Add(bindingTM);

        //associate command
        menuAppend.Command = Commands.Appender;

I would like to be able to use the Appender command on any TextBox on the Window, without the need to add the command binding to each TextBox.

-> Why doesn't adding the command binding to Window doesn't work?
-> Any solutions?

+1  A: 

Try:

public static void AppenderExecuted(object target, ExecutedRoutedEventArgs e)  {  
    System.Windows.Controls.TextBox targetTbox = e.OriginalSource as System.Windows.Controls.TextBox;  
    if (targetTbox != null) {  
            targetTbox.Text += "AppendedText";  
    }  
}  
HCL