views:

53

answers:

2

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?

+3  A: 

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

Aviad P.
Thanks for reply, is it possible to it in XAML anyway?
Prashant
You can't 'mask' the normal `MouseDown` behavior in pure XAML.
Aviad P.
+1 for clever use of attached properties and `ItemContainerGenerator`, but see also my answer which solves the problem more simply using `GetContainerForItemOverride`
Ray Burns
+2  A: 

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.

Ray Burns
Good answer, I managed to implement my attached property solution, but it turned out just a little bit too complicated and tricky than I hoped! :)
Aviad P.