Ver Mensaje Individual
  #4 (permalink)  
Antiguo 08/10/2015, 23:46
agleiva
(Desactivado)
 
Fecha de Ingreso: enero-2015
Mensajes: 393
Antigüedad: 9 años, 3 meses
Puntos: 52
Respuesta: Eliminar Item en un ListView en WPF desde un boton

Mira, te hice un ejemplo rápido para que veas como hacer esto usando DataBinding en WPF:

1 - Primero creamos una clase que implemente INotifyPropertyChanged (*1):

Código C#:
Ver original
  1. using System.ComponentModel;
  2.     using System.Runtime.CompilerServices;
  3.    
  4.     public class PropertyChangedBase : INotifyPropertyChanged
  5.     {
  6.         public event PropertyChangedEventHandler PropertyChanged;
  7.  
  8.         public void OnPropertyChanged([CallerMemberName]string propertyName = "")
  9.         {
  10.             var handler = this.PropertyChanged;
  11.             if (handler != null)
  12.                 handler(this, new PropertyChangedEventArgs(propertyName));
  13.         }
  14.     }

2 - Luego definimos nuestro modelo de datos a partir de esta clase base :

Código C#:
Ver original
  1. public class Person: PropertyChangedBase
  2.     {
  3.         private string _firstName;
  4.         public string FirstName
  5.         {
  6.             get { return _firstName; }
  7.             set
  8.             {
  9.                 _firstName = value;
  10.                 OnPropertyChanged();
  11.             }
  12.         }
  13.  
  14.         private string _lastName;
  15.         public string LastName
  16.         {
  17.             get { return _lastName; }
  18.             set
  19.             {
  20.                 _lastName = value;
  21.                 OnPropertyChanged();
  22.             }
  23.         }
  24.     }

3 - Creamos un ViewModel que contenga la collection de Person, y una propiedad SelectedPerson que representa el elemento seleccionado de la lista:

Código C#:
Ver original
  1. public class ViewModel: PropertyChangedBase
  2.     {
  3.         public ObservableCollection<Person> People { get; private set; }
  4.  
  5.         private Person _selectedPerson;
  6.         public Person SelectedPerson
  7.         {
  8.             get { return _selectedPerson; }
  9.             set
  10.             {
  11.                 _selectedPerson = value;
  12.                 OnPropertyChanged();
  13.             }
  14.         }
  15.  
  16.         public ViewModel()
  17.         {
  18.             var people = new[]
  19.             {
  20.                 new Person { FirstName = "Juán", LastName = "Pérez" },
  21.                 new Person { FirstName = "Ricardo", LastName = "Gómez" },
  22.                 new Person { FirstName = "Susana", LastName = "Gutierrez" }
  23.             };
  24.  
  25.             this.People = new ObservableCollection<Person>(people);
  26.             this.SelectedPerson = this.People.First();
  27.         }
  28.     }

4 - Asignamos una instancia de esta clase al DataContext de la vista, y agregamos los handlers del click de los botones para agregar y quitar elementos:

Código C#:
Ver original
  1. public partial class MainWindow : Window
  2.     {
  3.         public MainWindow()
  4.         {
  5.             InitializeComponent();
  6.             this.DataContext = new ViewModel();
  7.         }
  8.  
  9.         private void Agregar_Click(object sender, RoutedEventArgs e)
  10.         {
  11.             var vm = this.DataContext as ViewModel;
  12.             vm.People.Add(new Person { LastName = "[Apellido]", FirstName = "[Nombre]" });
  13.         }
  14.  
  15.         private void Quitar_Click(object sender, RoutedEventArgs e)
  16.         {
  17.             var vm = this.DataContext as ViewModel;
  18.             if (vm.SelectedPerson != null)
  19.             {
  20.                 vm.People.Remove(vm.SelectedPerson);
  21.             }
  22.         }
  23.     }

5 - Finalmente algo de XAML:

Código XAML:
Ver original
  1. <Window x:Class="WpfApplication2.MainWindow"
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.         Title="MainWindow" Height="350" Width="525">
  5.     <Grid>
  6.         <Grid.RowDefinitions>
  7.             <RowDefinition Height="Auto"/>
  8.             <RowDefinition Height="Auto"/>
  9.             <RowDefinition/>
  10.         </Grid.RowDefinitions>
  11.  
  12.         <Grid.ColumnDefinitions>
  13.             <ColumnDefinition Width="Auto"/>
  14.             <ColumnDefinition/>
  15.             <ColumnDefinition Width="Auto"/>
  16.         </Grid.ColumnDefinitions>
  17.        
  18.         <Label Content="Nombre:" Grid.Row="0" Grid.Column="0"/>
  19.         <Label Content="Apellido:" Grid.Row="1" Grid.Column="0"/>
  20.  
  21.         <TextBox Text="{Binding SelectedPerson.FirstName}" Grid.Row="0" Grid.Column="1" Margin="3"/>
  22.         <TextBox Text="{Binding SelectedPerson.LastName}" Grid.Row="1" Grid.Column="1" Margin="3"/>
  23.        
  24.         <Button Content="Agregar" Grid.Row="0" Grid.Column="2" Margin="3" Click="Agregar_Click"/>
  25.         <Button Content="Quitar" Grid.Row="1" Grid.Column="2" Margin="3" Click="Quitar_Click"/>
  26.  
  27.         <ListView ItemsSource="{Binding People}"
  28.                   SelectedItem="{Binding SelectedPerson}"
  29.                   Grid.Row="2" Grid.ColumnSpan="3">
  30.             <ListView.View>
  31.                 <GridView>
  32.                     <GridViewColumn Header="Nombre" DisplayMemberBinding="{Binding FirstName}" Width="200"/>
  33.                     <GridViewColumn Header="Apellido" DisplayMemberBinding="{Binding LastName}" Width="200"/>
  34.                 </GridView>
  35.             </ListView.View>
  36.         </ListView>
  37.     </Grid>
  38. </Window>

Fijate que al seleccionar items en la lista, se populan automáticamente los TextBox, y al cambiar el texto en los textbox se actualizan los datos en el ListView, y TODO sin escribir una línea de código, sino que WPF lo hace automáticamente mediante DataBinding.

Probá este código y te vas a dar cuenta.

(*1) Esto lo trae cualquier MVVM Framework como Caliburn.Micro, MVVM Light, MVVMCross, Prism, etc. etc. Muchas personas sugieren que siempre se debe usar uno de estos frameworks para crear aplicaciones en WPF, yo personalmente me he creado uno propio tomando cosas de cada uno de ellos.