Jatin Kapoor
Jatin Kapoor

Reputation: 3

Deleting and Editing an item in a listview with Viewmodel and without using the codebehind

In the shown code i need to know the coding to be replaced in place of question mark in the code. I need to delete,edit and update the item in the list view without writing any code in code behind. I only want to do these operations by bindin view with view model through Icommand

This a class in my model Playlist.cs

namespace MvvmDemo.Models { public class Playlist { public string Title { get; set; } } }

This is a class in my viewmodel PlaylistsViewModel.cs

namespace MvvmDemo.ViewModels { public class PlaylistsViewModel { public ObservableCollection Playlists { get; private set; } = new ObservableCollection();

    public ICommand AddPlaylistCommand { get; private set; }

    public ICommand DeletePlaylistCommand { get; private set; }

     public ICommand EditPlaylistCommand { get; private set; }

    public PlaylistsViewModel()
    {
        AddPlaylistCommand = new Command(AddPlaylist);
        DeletePlaylistCommand = new Command(DeletePlaylist);
    }

    public void AddPlaylist()
    { 
        var newPlaylist = "Playlist " + (Playlists.Count + 1);
        Playlists.Add(new Playlist { Title = newPlaylist });
    }

    public void DeletePlaylist()
    {
        ????????????????
    }
    public void EditPlaylist()
    {
        ????????????????
    }
}

}

Upvotes: 0

Views: 1320

Answers (3)

Karan Rami
Karan Rami

Reputation: 321

You can use observablecollection. It will reflect add,remove operation of item to the listview. And for editing item you have to raise property changed for all property you are editing.To simplify that property changed you can implement property changed event to your Playlist model class.

Like

public void DeletePlaylist()
    {
        Playlists.Remove(newPlaylist);
    }
    public void EditPlaylist()
    {
        newPlaylist.Title="Refreshed Playlist"
    }

public class Playlist:INotifyPropertyChanged
{
    private string title;
    public string Title
    {
       get{return title;}
       set{title=value;
           NotifyPropertyChanged();}  
    }
}

Upvotes: 0

Cherry Bu - MSFT
Cherry Bu - MSFT

Reputation: 10356

If you want to delete and edit item in ListView, firstly, you should need to use ICommand, then you could need to use INotifyPropertyChanged to implement Inotify. I do one sample that you can take a look. Choosing one Item and long press with the left mouse button, you will see two ways, delete Item and Edit Item action.

 <ContentPage.Content>
    <StackLayout>
        <ListView
            x:Name="mylistview"
            ItemsSource="{Binding lists}"
            SelectedItem="{Binding selecteditem}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.ContextActions>
                            <MenuItem
                                Command="{Binding BindingContext.DeletePlaylistCommand, Source={x:Reference Name=mylistview}}"
                                IsDestructive="true"
                                Text="Delete Item" />
                            <MenuItem
                                Command="{Binding BindingContext.EditPlaylistCommand, Source={x:Reference Name=mylistview}}"
                                IsDestructive="true"
                                Text="Edit Item" />
                        </ViewCell.ContextActions>
                        <StackLayout Padding="15,0">
                            <Label Text="{Binding Title}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage.Content>


[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page19 : ContentPage, INotifyPropertyChanged
{
    public ObservableCollection<Playlist> lists { get; set; }
    //public RelayCommand1 AddPlaylistCommand { get; set; }
    public RelayCommand DeletePlaylistCommand { get; set; }
    public RelayCommand EditPlaylistCommand { get; set; }

    private Playlist _selecteditem;
    public Playlist selecteditem
    {
        get { return _selecteditem; }
        set
        {
            _selecteditem = value;
            RaisePropertyChanged("selecteditem");

        }
    }

    public Page19 ()
    {
        InitializeComponent ();
        lists = new ObservableCollection<Playlist>()
        {
            new Playlist(){Id=1,Title="list 1"},
             new Playlist(){Id=2, Title="list 2"},
              new Playlist(){Id=3,Title="list 3"},
               new Playlist(){Id=4,Title="list 4"},
                new Playlist(){Id=5,Title="list 5"},
                new Playlist(){Id=6,Title="list 6"},
        };

        DeletePlaylistCommand = new RelayCommand(DeletePlaylist);
        EditPlaylistCommand = new RelayCommand(EditPlaylist);
        selecteditem = lists[0];
        this.BindingContext = this;
    }

    public void AddPlaylist()
    {

    }

    public void DeletePlaylist()
    {
        Playlist item = selecteditem;
        lists.Remove(item);

    }

    public void EditPlaylist()
    {
        Playlist item = selecteditem;
        int id = item.Id;
        foreach(Playlist playl in lists.Where(a=>a.Id==id))
        {
            playl.Title = "chenge title";
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;


    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

public class Playlist: INotifyPropertyChanged
{
    private int _Id;
    public int Id
    {
        get { return _Id; }
        set
        {
            _Id = value;
            RaisePropertyChanged("Id");
        }
    }
    private string _Title;
    public string Title
    {
        get { return _Title;}
        set
        {
            _Title = value;
            RaisePropertyChanged("Title");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;


    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}

Here is the RelayCommd:

 public class RelayCommand : ICommand
{
    readonly Action _execute;

    public RelayCommand(Action execute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
    }

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return true;
    }
    public void Execute(object parameter)
    {
        _execute();
    }

}

enter image description here

Upvotes: 1

Akhil George
Akhil George

Reputation: 124

you have to make the command is parameterised and pass binding data through the parameter. and from that data you can get the index value of selected.using that remove the item from the list.

Playlists.RemoveAt("INDEX_NUMBER");

To update it in the view use "INotifyProperty" also

Upvotes: 0

Related Questions