tags:

views:

24

answers:

1

I have a ListBox with ItemsTemplate set.

Now I want to catch Ctrl + Left click on a ListBoxItem.

I found KeyBoard class that should give me modifier keys. Now how do I get the click event on the ListBoxItem? Even better, how do I bind it to ICommand.

I found some bits and pieces but don't know how to connect them. It seems InputBinding seems could help me or EventSetter.

+1  A: 

Below is a simple example that handles Ctrl + PreviewMouseLeftButtonDown using an EventSetter in the ListBoxItem's Style. This is probably what you want.

XAML:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown"/>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <s:String>Item1</s:String>
    <s:String>Item2</s:String>
    <s:String>Item3</s:String>
    <s:String>Item4</s:String>
</ListBox>

Code-Behind:

void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)
    {
        Console.WriteLine((sender as ListBoxItem).Content.ToString());
        e.Handled = false;
    }
}

To bind it to an ICommand, you can use an attached behavior like the EventToCommand behavior discussed here.

EDIT:

To address your comment, handling the Click-event will be a bit tricky for the ListBoxItem because of two things: 1) The ListBoxItem doesn't have a click event, and 2) The ListBoxItem internally handles some of the MouseEvents. Anyway, I came up with a simulated, attached ClickEvent to make it work. See below. Hope it works.

public class AttachedEvents
{
    private static readonly DependencyProperty IsTriggerEnabledProperty =
        DependencyProperty.RegisterAttached("IsTriggerEnabled", typeof(bool), typeof(FrameworkElement), new FrameworkPropertyMetadata(false));

    public static readonly RoutedEvent ClickEvent;

    static AttachedEvents()
    {
        try
        {
            ClickEvent = EventManager.RegisterRoutedEvent("Click",
                                                        RoutingStrategy.Bubble,
                                                        typeof(RoutedEventHandler),
                                                        typeof(FrameworkElement));
        }
        catch (Exception ex)
        { }
    }


    private static void SetIsTriggerEnabled(FrameworkElement element, bool value)
    {
        if (element != null)
        {
            element.SetValue(IsTriggerEnabledProperty, value);
        }
    }

    private static bool GetIsTriggerEnabled(FrameworkElement element)
    {
        return (element != null) ? (bool)element.GetValue(IsTriggerEnabledProperty) : false;
    }

    public static void AddClickHandler(DependencyObject o, RoutedEventHandler handler)
    {
        FrameworkElement element = (FrameworkElement)o;
        element.AddHandler(ClickEvent, handler);
        element.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(SimulatedClick_MouseLeftButtonUp);
        element.PreviewMouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(SimulatedClick_MouseLeftButtonDown);
    }

    public static void RemoveClickHandler(DependencyObject o, RoutedEventHandler handler)
    {
        FrameworkElement element = (FrameworkElement)o;
        element.RemoveHandler(ClickEvent, handler);
        element.MouseLeftButtonUp -= new System.Windows.Input.MouseButtonEventHandler(SimulatedClick_MouseLeftButtonUp);
        element.PreviewMouseLeftButtonDown -= new System.Windows.Input.MouseButtonEventHandler(SimulatedClick_MouseLeftButtonDown);
    }

    static void SimulatedClick_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;
        UpdateIsTriggerSet(element);
        Mouse.Capture(element);
    }

    static void SimulatedClick_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;

        bool isTriggerSet = (bool)element.GetValue(IsTriggerEnabledProperty);

        // update the trigger set flag
        UpdateIsTriggerSet(element);

        //release the mouse capture
        Mouse.Capture(null);

        // if trigger is set and we are still over the element then we fire the click event
        if (isTriggerSet && IsMouseOver(element))
        {
            element.RaiseEvent(new RoutedEventArgs(ClickEvent, sender));
        }

    }

    private static bool IsMouseOver(FrameworkElement element)
    {
        Point position = Mouse.PrimaryDevice.GetPosition(element);
        if (((position.X >= 0.0) && (position.X <= element.ActualWidth)) && ((position.Y >= 0.0) && (position.Y <= element.ActualHeight)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private static void UpdateIsTriggerSet(FrameworkElement element)
    {
        Point position = Mouse.PrimaryDevice.GetPosition(element);
        if (((position.X >= 0.0) && (position.X <= element.ActualWidth)) && ((position.Y >= 0.0) && (position.Y <= element.ActualHeight)))
        {
            if (!(bool)element.GetValue(IsTriggerEnabledProperty))
            {
                element.SetValue(IsTriggerEnabledProperty, true);
            }
        }
        else if ((bool)element.GetValue(IsTriggerEnabledProperty))
        {
            element.SetValue(IsTriggerEnabledProperty, false);
        }
    }
}

Sample usage is shown below. I can't seem to set the attached event in XAML (I'm not sure why) so I had to do a workaround here. What I do is wait 'til the ListBoxItem gets loaded and Attach the event handler in the code-behind.

XAML:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="Loaded" Handler="OnLoaded"/>
        </Style>
    </ListBox.ItemContainerStyle>
...
</ListBox>

Code-Behind:

void OnLoaded(object sender, RoutedEventArgs e)
{
    AttachedEvents.AddClickHandler((sender as ListBoxItem), HandleClick);
}

void HandleClick(object sender, RoutedEventArgs e) 
{
    if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)
    {
        Console.WriteLine("Ctrl + Clicked!");
    }
}
karmicpuppet
MouseLeftButtonDown isn't really a Click.
Kugel
You're right. I just thought MouseDown will be good enough. Anyway, see EDIT. It's quite a fairly lengthy solution but I hope it works.
karmicpuppet
Thank you for your insight. I learned a lot from your post.
Kugel