Double Click a ListBox item to open a browser

后端 未结 5 738
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 04:28

I have a ListBox in my wpf window that binds to an ObervableCollection. I want to open the browser if someone clicks on an element of the Li

5条回答
  •  温柔的废话
    2020-12-05 04:48

    I wanted to solve this without needing to handle the listBoxItem double click event in the code-behind, and I didn't want to have to override the listBoxItem style (or define the style to override in the first place). I wanted to just fire a command when the listBox was doubleclicked.

    I created an attached property like so (the code is very specific, but you can generalise it as required):

    public class ControlItemDoubleClick : DependencyObject {
    public ControlItemDoubleClick()
    {
    
    }
    
    public static readonly DependencyProperty ItemsDoubleClickProperty =
        DependencyProperty.RegisterAttached("ItemsDoubleClick",
        typeof(bool), typeof(Binding));
    
    public static void SetItemsDoubleClick(ItemsControl element, bool value)
    {
        element.SetValue(ItemsDoubleClickProperty, value);
    
        if (value)
        {
            element.PreviewMouseDoubleClick += new MouseButtonEventHandler(element_PreviewMouseDoubleClick);
        }
    }
    
    static void element_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ItemsControl control = sender as ItemsControl;
    
        foreach (InputBinding b in control.InputBindings)
        {
            if (!(b is MouseBinding))
            {
                continue;
            }
    
            if (b.Gesture != null
                && b.Gesture is MouseGesture
                && ((MouseGesture)b.Gesture).MouseAction == MouseAction.LeftDoubleClick
                && b.Command.CanExecute(null))
            {
                b.Command.Execute(null);
                e.Handled = true;
            }
        }
    }
    
    public static bool GetItemsDoubleClick(ItemsControl element)
    {
        return (bool)element.GetValue(ItemsDoubleClickProperty);
    }
    

    }

    I then declare my ListBox with the attached property and my target command:

    
    
        
    
    
    

    Hope this helps.

提交回复
热议问题