views:

278

answers:

2

How do I delete a selected ListViewItem from a WPF ListView when the ItemsSource is set to a DataView? I can get the ListViewItem that was selected and then how do remove the actual row in the DataView?

DataView dv = (DataView)myListView.ItemsSource;
ListViewItem lvi = (ListViewItem)myListView.ItemContainerGenerator.ContainerFromItem(myListView.SelectedItem);
<Delete ListViewItem here>
+1  A: 

When you bind your collection to the listview, use ListCollectionView instead of DataView. Can be easily done like this (where dataView is of type DataView):

ListCollectionView lcv = new ListCollectionView(dataView);
myListView.ItemsSource = lcv;

Now when you need to delete any object, just do this:

ListCollectionView lcv = (ListCollectionView) myListView.ItemsSource;
lcv.Remove(myListView.SelectedItem);

And after deleting, just refresh the view:

lcv.Refresh();

or

((ListCollectionView)myListView.ItemsSource).Refresh();
Yogesh
A: 

Consider using the M-V-VM pattern to separate the notion of removing an item from your list of data objects and DIRECTLY removing them from your current UI implementation. The two do not need to know about each other, aside from Bindings.

When you use the MVVM pattern, expose a boolean "IsSelected" property in your ViewModel.

public class SimpleViewModel : BaseViewModel //For INotifyPropertyChanged, etc
{

      public IList<SimpleBusinessObject> ViewModelItems;

      public SimpleViewModel()
      {
             ViewModelItems = new ObservableList<SimpleBusinessObjectViewModel>();
      }

}

public class SimpleBusinessObjectViewModel
{
      public bool ViewModelIsSelected { get; set; }

      public SimpleBusinessObjectViewModel()
      {
             ViewModelIsSelected = false;
      }
}

Next, in your View try something like this:

<Style TargetType="{x:Type ListViewItem}">
       <Style.Triggers>
               <Setter Property="IsSelected" Value="{Binding ViewModelIsSelected}"
       </Style.Triggers>
</Style>
<ListView ItemsSource={Binding ViewModelItems}>   
       //here you can insert how you want to display a ListViewItem
</ListView>

This will let you add, edit, and remove items in your ViewModel's List -- just like if it were the actual ListView. From here, you can also check each item's IsSelected (that responds to mouse interactions with the ListView) without actually checking the ListViewItem. This will be a much cleaner, maintainable solution.

Jimmy Lyke
Your Business Object knows about your ViewModel? This isn't a very good idea as it reverses the normal separation of business logic and presentation logic.
jpierson
Great point. I'll update my example.
Jimmy Lyke