Delete an item in a listbox with a button, in wpf MVVM
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 开发者_Go百科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:
- First, Don't forget to bind your
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 all - Second, your command here is never created. Let me explain. You are binding the Delete button to your command Commands. It has a getter. However, if you call get, what will it return? Nothing, the command is null...
Here 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):
/// <summary>
/// Class representing a command sent by a button in the UI, defines what to launch when the command is called
/// </summary>
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
//[DebuggerStepThrough]
/// <summary>
/// Defines if the current command can be executed or not
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
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):
private RelayCommand _deleteCommand;
public ICommand DeleteCommand
{
get
{
if (_deleteCommand == null)
{
_deleteCommand = new RelayCommand(param => DeleteItem());
}
return _deleteCommand;
}
}
This means that when you call your command, it will call the function DeleteItem
The only thing left to do is:
private void DeleteItem() {
//First step: copy the actual list to a temporary one
ObservableCollection<ExaminationQuestion> tempCollection = new ObservableCollection<ExaminationQuestion>(this.Examination.ExaminationQuestions);
//Then, iterate on the temporary one:
foreach (ExaminationQuestion exaq in tempCollection)
{
if (exaq.Question.Guid == SelectedQuestionDropList.Guid)
{
//And remove from the real list!
this.Examination.ExaminationQuestions.Remove(exaq);
SelectedQuestions.Remove(SelectedQuestionDropList);
OnPropertyChanged("SelectedQuestions");
}
}
}
And there you go :)
精彩评论