开发者

How to delete a ListViewItem when bound to a DataView

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> 


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();


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜