Search code examples
c#wpfmvvmdatagridcaliburn.micro

Delete duplicate rows in datagrid Wpf MVVM?


Im trying to delete duplicate elements in DataGrid, when I add new element from TextBox. Maybe, anyone has an idea how to solve it?

public class ShellViewModel : Screen
{
   private string _input = string.Empty;
    public ObservableCollection<Person> people;

    public ShellViewModel()
    {

    }

    public string Input
    {
        get
        {
            return _input;
        }
        set
        {
            _input = value;
            NotifyOfPropertyChange(() => Input);
        }
    }       

    public ObservableCollection<Person> People
    {
        get
        {
            return people;
        }
        set
        {
            people = value;
            NotifyOfPropertyChange(() => People);
        }
    }

    Person person = new Person();
    ObservableCollection<Person> persons = new ObservableCollection<Person>();
    public void Write()
    {
         person.name = Input;
         persons.Add(person);         
         People = persons;                     
    }
   }

I dont have any problems with adding elements to DataGrid, but I dont know how to delete duplicate elements. Thank you in advance.


Solution

  • You have to check if the Person already exists before adding it to the collection.

    I also fixed some issues with your code. Since People is a ObservableCollection you can add items to it directly and the view will register the changes in the collection and update immediately.
    You should also create a new instance of Person when adding it to the collection, otherwise you would overwrite the existing one. You are currently using a single Person. Fields should always be private.

    public class ShellViewModel : Screen
    { 
        public void ShellViewModel()
        {
          this.Input = string.Empty;
          this.People = new ObservableCollection<People>();      
        }
    
        private string _input = string.Empty;
        public string Input
        {
            get => _input;
            set
            {
                _input = value;
                NotifyOfPropertyChange(() => Input);
            }
        }       
    
        private ObservableCollection<Person> people;
        public ObservableCollection<Person> People
        {
            get => people;
            set
            {
                people = value;
                NotifyOfPropertyChange(() => People);
            }
        }
    
        public void Write()
        {
          if (string.IsNullOrWhiteSpace(this.input) 
            || this.People.Any(person => person.name.Equals(this.Input, StringComparison.OrdinalIgnoreCase))
          {
            return;
          }
    
          Person newPerson = new Person() {name = this.Input};
          this.People.Add(newPerson);      
       }
    }