I have a problem. It seems a simple thing but it isn't that easy. I have two listboxes, with objects in it. One is full with available objects and the other is empty, and I can fill this up with drag and drop. If you fill this empty listbox, the items are also added to a list of, this is a property of another object. But now my question is how I can easily delete an object in this listbox by clicking on a button.
I tried something but it wouldn't run. Here is my xaml:
<ListBox ItemsSource="{Binding AvailableQuestions}"
DisplayMemberPath="Description"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True" Margin="0,34,0,339" Background="#CDC5CBC5"
dd:DragDrop.DropHandler="{Binding}"/>
<ListBox SelectedItem="{Binding Path=SelectedQuestionDropList, UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ItemsSource="{Binding SelectedQuestions}"
DisplayMemberPath="Description"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True" Margin="0,201,0,204" Background="#CDC5CBC5"
dd:DragDrop.DropHandler="{Binding}" />
<Button Content="Delete" Height="23"
HorizontalAlignment="Left"
Margin="513,322,0,0"
Name="button1"
VerticalAlignment="Top" Width="75" Command="{Binding Commands}"
CommandParameter="Delete" />
here is my viewmodel:
// other stuff and properties..
public ICommand Commands { get; set; }
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested += value; }
}
public void Execute(Object parameter)
{
foreach (ExaminationQuestion exaq in this.Examination.ExaminationQuestions)
{
if (exaq.Question.Guid == SelectedQuestionDropList.Guid)
{
this.Examination.ExaminationQuestions.Remove(exaq);
SelectedQuestions.Remove(SelectedQuestionDropList);
OnPropertyChanged("SelectedQuestions");
}
}
}
can somebody please help me out?
You need to know two things:
ListBox
to anObservableCollection
rather than to a classic IList. Otherwise, if your command is actually fired and removes an item from the list, the UI wouldn't change at allHere is the way I'd advise you to work: Create a generic command class (I called it RelayCommand, following a tutorial... but the name doesn't matter):
Then, in your ViewModel, create a property command, and define the actual getter (you don't have to use the setter, you can just forget it):
This means that when you call your command, it will call the function
DeleteItem
The only thing left to do is:
And there you go :)