Where can I find the CommandTarget?

661 views Asked by At

I am still making experiences with Commands and RoutedEvents. Without using RoutedCommands, I try to realize a ver simple program.

Here is my Command class:

public class ColorChanger : ICommand
{
    public static readonly RoutedEvent ChangeMyColor = EventManager.RegisterRoutedEvent("ChangeMyColor", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(ColorChanger));

    public void Execute(object parameter)
    {
        RoutedEventArgs eventArgs  = new RoutedEventArgs(ChangeMyColor);
        Keyboard.FocusedElement.RaiseEvent(eventArgs);
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public static void AddChangeMyColorHandler(DependencyObject o, RoutedEventHandler handler)
    {
        ((UIElement)o).AddHandler(ColorChanger.ChangeMyColor, handler);
    }

    public static void RemoveChangeMyColorHandler(DependencyObject o, RoutedEventHandler handler)
    {
        ((UIElement)o).AddHandler(ColorChanger.ChangeMyColor, handler);
    }
}

To make sure I have a static access to that command, I made a static class for holding all commands:

 public static class AppCommands
{
    private static ColorChanger colorChanger = new ColorChanger();

    public static ColorChanger ColorChanger
    {
        get { return colorChanger; }
    }
}

This is what you will find in my MainWindow.xaml:

<StackPanel>
    <Menu>
        <MenuItem Command="{x:Static local:AppCommands.ColorChanger}" Header="ClickMe"
          CommandTarget="{Binding ElementName=mainTextBox}" x:Name="menue1"/>
    </Menu>
    <TextBox Name="mainTextBox"/>
</StackPanel>

What I want is that by clicking the menue1-item the background of the 'mainTextBox' changes. So let's have a look inside my MainWindow.cs:

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        AddHandler(ColorChanger.ChangeMyColor,new RoutedEventHandler(test));
    }

    public void test(object sender, RoutedEventArgs args)
    {
        Control someCtl = (Control) args.OriginalSource;
        someCtl.Background = Brushes.BlueViolet;
    }
}

The programm is working - but not correct :) It always changes the background of the MainWindow, but not of my CommandTarget.

So - what am I doing wrong? Did I forget something?

1

There are 1 answers

0
mikelowe On

OriginalSource is the reporting source of an event based on pure hit testing. See: http://msdn.microsoft.com/en-us/library/system.windows.routedeventargs.originalsource.aspx.

In this case it returns your window because it doesn't resolve to any of child elements in its visual tree.

To access your CommandTarget you should use args.Source.