Question

For a very specific reason I want to select ListViewItems on mouse button up, not actually on mouse button down. I want this behaviour to be embedded in the control. Is it possible to achieve this? can anyone give hint?

Was it helpful?

Solution

Aviad P.'s answer is a good one and a clever use of attached properties, but I tend to use a different technique most of the time:

  1. Subclass ListViewItem.
  2. Override OnMouseLeftButtonDown and OnMouseRightButton to do nothing.
  3. Override OnMouseLeftButtonUp / OnMouseRightButtonUp to call base.OnMouseLeftButtonDown / base.OnMouseRightButtonDown.
  4. Subclass ListView.
  5. Override GetContainerForItemOverride() to return your ListViewItem override

This seems easier to me than subscribing to ItemContainer events and adding handlers dynamically.

This is what it looks like:

public class MouseUpListViewItem : ListViewItem
{
  protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {}
  protected override void OnMouseRightButtonDown(MouseButtonEventArgs e) {}

  protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
  {
    base.OnMouseLeftButtonDown(e);
  }
  protected override void OnMouseRightButtonUp(MouseButtonEventArgs e)
  {
    base.OnMouseRightButtonDown(e);
  }
}
public class MouseUpListView : ListView
{
  protected override DependencyObject GetContainerForItemOverride()
  {
    return new MouseUpListViewItem();
  }
}

I like this technique because there is less code involved.

OTHER TIPS

Yes it's definitely possible using attached properties. Define an attached property called SelectOnMouseUp and when it's set to true, hook to your ItemsContainerGenerator events to discover when a new item container is added. Then when you get an event for a new item container, hook into its PreviewMouseDown and ignore it (set e.Handled to true), and hook into its MouseUp event and perform the selection (set IsSelected to true).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top