how to remove custome items from observablecollect

2019-09-08 01:36发布

问题:

i binded one observable cllection to one listbox in silverlight.when i click one item in listbox and click delete button ,how to remove that particular item remove from the listbox without linq using mvvm.i passed commandparameter of the button is listbox itemid.

 <ListBox   ItemsSource="{Binding School1,Mode=TwoWay}" DisplayMemberPath="SchoolName"  Name="listBox1"  >
<Button Content="Delete" Command="{Binding deletecommand}" CommandParameter="{Binding Path=SelectedItem.ID,ElementName=listBox1}"   Name="button2" />

so what is the code for remove particular item from observable collection

public void delete(object parameter)
{
School1.Remove(...)
}

回答1:

Bind the ListBox's SelectedItem to a property and use that in your Remove():

 <ListBox ItemsSource="{Binding School1, Mode=TwoWay}" 
          DisplayMemberPath="SchoolName"  
          SelectedItem={Binding SelectedSchool}
          Name="listBox1"  
          />


public void delete(object parameter)
{
    if (SelectedSchool != null)
        School1.Remove(SelectedSchool);
}

Also note that your question is somewhat of a duplicate: Clearing selecteditem of listbox (which is bound to collection of objects) with MVVM