Frage

Related: "Cleanest single click + double click handling in Silverlight?"


What is the simplest way to make a double-click trigger some action in XAML?

I'm trying to do something like this, closing a popup when the user double-clicks a ListBox item:

<Popup x:Name="popup">
    <ListBox ItemsSource="{Binding Colors}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Rectangle Color="{Binding Color}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="DoubleClick">
                            <ei:ChangePropertyAction TargetObject="{Binding ElementName=popup}"
                                                     PropertyName="IsOpen" Value="False" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Rectangle>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ListBox>
</Popup>

The problem with this above is that, of course, there is no "DoubleClick" event. So I need to replace the EventTrigger with a double-click trigger.

War es hilfreich?

Lösung

Create a custom double-click trigger by inheriting TriggerBase<T> and attaching a listener to the "MouseLeftButtonDown" event. Check the "MouseButtonEventArgs.ClickCount" property to check for the double-click:

public class DoubleClickTrigger : TriggerBase<FrameworkElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.AddHandler(FrameworkElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnClick), true);
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.RemoveHandler(FrameworkElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(OnClick));
    }

    private void OnClick(object sender, MouseButtonEventArgs args)
    {
        if (args.ClickCount == 1)
            return;
        if (args.ClickCount == 2)
            InvokeActions(null);
    }
}

With this, the XAML in the OP should work by replacing the EventTrigger with the above DoubleClickTrigger.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top