WPF将鼠标悬停在组合框上时从组合框中删除项目(MVVM)

本文关键字:组合 删除项目 MVVM 鼠标 悬停 WPF | 更新日期: 2023-09-27 18:21:55

我有一个绑定到Observable Collection的组合框。Collection是一个自定义类的容器。

当鼠标光标悬停在下拉列表的项目上时,我需要通过按下鼠标右键从组合框中删除任意项目。我还需要在项目高亮显示时按下删除按钮来删除它。

我已经在代码后面有了一个解决方案,但我需要使用MVVM模式来完成它。

有人能在这个问题上帮我吗?

Thx提前:)。

这是我的代码:

我的视图模型:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Catel.MVVM;
using System.Windows.Input;
using DeleteItemFromComboBox.Models;
using Catel.Data;
namespace DeleteItemFromComboBox.ViewModels
{
    public class MainWindowVM : ViewModelBase
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindowVM"/> class.
        /// </summary>
        public MainWindowVM()
        {
            PreviewKeyDownCmd = new Command<KeyEventArgs>(PreviewKeyDownCmdExecute);
            PersonList = new ObservableCollection<Person>();
            PersonList.Add(new Person("AA"));
            PersonList.Add(new Person("BB"));
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the property value.
        /// </summary>
        public ObservableCollection<Person> PersonList
        {
            get { return GetValue<ObservableCollection<Person>>(PersonListProperty); }
            set { SetValue(PersonListProperty, value); }
        }
        /// <summary>
        /// Register the PersonList property so it is known in the class.
        /// </summary>
        public static readonly PropertyData PersonListProperty = 
            RegisterProperty("PersonList", typeof(ObservableCollection<Person>), null);
        #endregion

        #region Commands
        /// <summary>
        /// Gets the PreviewKeyDownCmd command.
        /// </summary>
        public Command<KeyEventArgs> PreviewKeyDownCmd { get; private set; }
        /// <summary>
        /// Method to invoke when the PreviewKeyDownCmd command is executed.
        /// </summary>
        private void PreviewKeyDownCmdExecute(KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                //********************What Should i do here?***************************
            }
        }
        #endregion
    }
}

XAML文件:

<Window x:Class="DeleteItemFromComboBox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ViewModels="clr-namespace:DeleteItemFromComboBox.ViewModels"
    Title="MainWindow" Height="350" Width="525"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:catel="http://catel.codeplex.com">
<Window.Resources>
    <ViewModels:MainWindowVM x:Key="ViewModel"/>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModel}}">
    <ComboBox Height="44" 
              HorizontalAlignment="Left" 
              Margin="12,12,0,0" 
              Name="comboBox1" 
              VerticalAlignment="Top" 
              Width="479"
              ItemsSource="{Binding PersonList, Mode=TwoWay}" >
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="PreviewKeyDown">
                <catel:EventToCommand Command="{Binding PreviewKeyDownCmd}" DisableAssociatedObjectOnCannotExecute="False" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </ComboBox>
</Grid>

人员类别:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Catel.MVVM;
using Catel.Data;
using System.Runtime.Serialization;
namespace DeleteItemFromComboBox.Models
{
#if !SILVERLIGHT
    [Serializable]
#endif
    public class Person : ModelBase
    {
        #region Constructors
        public Person() { }
        public Person(string name)
        {
            this.Name = name;
        }
#if !SILVERLIGHT
        protected Person(SerializationInfo info, StreamingContext context)
            : base(info, context) { }
#endif
        #endregion
        /// <summary>
        /// Gets or sets the property value.
        /// </summary>
        [Model]
        public string Name
        {
            get { return GetValue<string>(NameProperty); }
            private set { SetValue(NameProperty, value); }
        }
        /// <summary>
        /// Register the Name property so it is known in the class.
        /// </summary>
        public static readonly PropertyData NameProperty = 
            RegisterProperty("Name", typeof(string));
        public override string ToString()
        {
            return Name;
        }
    }
}

非MVVM项目中的代码隐藏解决方案:

private void comboBox1_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Delete)
        {
            foreach (People item in comboBox1.Items)
            {
                ComboBoxItem cbi = this.comboBox1.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
                if (cbi.IsHighlighted == true)
                {
                    peoples.Remove(item);
                    return;
                }
            }
        }
    }

WPF将鼠标悬停在组合框上时从组合框中删除项目(MVVM)

最简单的方法是创建属性SelectedPerson。一旦用户右键单击某个项目,它就会自动设置SelectedPerson。然后,您还可以创建一个工具栏,该工具栏使用与弹出窗口相同的命令来删除列表中的选定项目。

当你使用SelectedPerson方法时,你可以使用这样的代码:

MyCollection.Remove(SelectedPerson);
SelectedPerson = null;

请确保在OnCanExecute中检查SelectedPerson!=无效的

我使用了其中一种方法来解决这个问题:

  1. 将MouseButtonEventArgs.Source投射到组合框中,然后应用我上面提到的解决方案来完成任务。只需删除您选择的类型的IPlan。

    private void Plan_PreviewMouseRightButtonDownCmd_Execute(MouseButtonEventArgs e)
    {
        ComboBox comboBox =  e.Source as ComboBox;
        if(comboBox!=null)
        {
            foreach (IPlan item in comboBox.Items)
            {
                ComboBoxItem cbi = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
                if (cbi.IsHighlighted == true)
                    SelectedPlans.Remove(item);
                if (item == SelectedPlan)
                    SelectedPlan = null;
            }
        }
    }
    
  2. 使用此自定义组合框实现,并将项索引绑定到代码隐藏中的属性。然后您可以通过MyCollection.RemoveAt()删除该项目;

http://www.codeproject.com/Articles/14255/ComboBox-firing-events-when-hovering-on-the-dropdo