tags:

views:

950

answers:

2

Is there a way to make the selectionchanged event fire every time a selection in the listview is clicked, instead of only when it changes?

For example, lets say i have a listview with only one object in it. The user clicks that object, and that object contains information that populates some textboxes below. The user starts changing some of the values in these textboxes (which are not bound to the object). They then decide that they dont want what is in those text boxes so they'd like to reset everything to what is in the object in the listview. But when they click the one object in the listview, nothing happens, because the selection has not changed.

Hope that makes sense. Anyone know how I can get around this?

A: 

The ListView.SelectionChanged and ListViewItem.Selected events are not going to re-fire if the item is already selected. If you need to re-fire it, you could 'deselect' the item when the event fires.

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
 foreach (var item in e.AddedItems.OfType<ListViewItem>())
 {
  Trace.WriteLine("ListViewItem Selected");
  item.IsSelected = false;
 }
}

Thus allowing you to re-select it ad nauseum. However, if you don't need the actual selection then you should be using an ItemsControl.

If you do want to maintain the select-ability of the item(s) then you should look at registering to a different event than ListView.SelectionChanged, or ListView.Selected. One that works well for this is PreviewMouseDown, as like the initial item selection we want it to occur on both left and right clicks. We could attach it to the single ListViewItem, but since the list may at some point gain more items, we can assign it to all items by using the ItemContainerStyle property of the ListView.

<ListView SelectionChanged="ListView_SelectionChanged">
 <ListView.ItemContainerStyle>
  <Style TargetType="{x:Type ListViewItem}">
   <EventSetter Event="PreviewMouseDown"
          Handler="ListViewItem_PreviewMouseDown" />
  </Style>
 </ListView.ItemContainerStyle>
 <ListViewItem>Item 1</ListViewItem>
 <ListViewItem>Item 2</ListViewItem>
 <ListViewItem>Item 3</ListViewItem>
 <ListViewItem>Item 4</ListViewItem>
</ListView>


private void ListViewItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
 Trace.WriteLine("ListViewItem Clicked: " + (sender as ListViewItem).Content);
}
rmoore
A: 

Thanks for your help, I solved it with a combination of selectionchanged and mouseleftbuttondown events. Works great :)