Prashant Cholachagudda
Prashant Cholachagudda

Reputation: 13092

WPF Listview modification

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?

Upvotes: 1

Views: 493

Answers (2)

Ray Burns
Ray Burns

Reputation: 62919

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.

Upvotes: 2

Aviad P.
Aviad P.

Reputation: 32639

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).

Upvotes: 3

Related Questions