在wpf MVVM中使用按钮删除列表框中的项目

Rub*_*ben 2 wpf listbox

我有个问题.这看起来很简单,但并不容易.我有两个列表框,其中包含对象.一个是可用对象,另一个是空的,我可以用拖放来填充它.如果填充此空列表框,则项目也会添加到列表中,这是另一个对象的属性.但现在我的问题是如何通过单击按钮轻松删除此列表框中的对象.

我尝试了一些东西,但它不会运行.这是我的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" />
Run Code Online (Sandbox Code Playgroud)

这是我的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");
        }
    }               
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

Dam*_*cus 6

你需要知道两件事:

  • 首先,不要忘了你的绑定ListBox到一个ObservableCollection,而不是一个经典的IList.否则,如果您的命令实际被触发并从列表中删除项目,则UI根本不会更改
  • 其次,这里的命令永远不会被创建.让我解释.您正在将"删除"按钮绑定到命令"命令".它有一个吸气剂.但是,如果你打电话给get,它会返回什么?没什么,命令是空的......

这是我建议你工作的方式:创建一个通用命令类(我称之为RelayCommand,遵循教程......但名称无关紧要):

/// <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
    }
Run Code Online (Sandbox Code Playgroud)

然后,在ViewModel中,创建一个属性命令,并定义实际的getter(你不必使用setter,你可以忘记它):

private RelayCommand _deleteCommand;

public ICommand DeleteCommand
        {
            get
            {
                if (_deleteCommand == null)
                {
                    _deleteCommand = new RelayCommand(param => DeleteItem());
                }
                return _deleteCommand;
            }
        }
Run Code Online (Sandbox Code Playgroud)

这意味着当您调用命令时,它将调用该函数 DeleteItem

剩下要做的唯一事情是:

   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");
                    }
                }
    }
Run Code Online (Sandbox Code Playgroud)

那你去:)