Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

How to wire up a DeleteCommand in this simple MVVM project?

$
0
0

I have piece mealed together a simple MVVM project from various code snippets -- using VS2012 (with no toolkits like MVVMLight, Prism, ...).  The project contains a listbox with two entries that get loaded on project startup and a Delete button which is suppoed to be able to remove a selected entry from the listbox.  I am able to populate the listbox on project startup using an observableCollection that is based on the model (ContactModel).  Again, I have piece mealed this together from various code snippets, so some of the snippets may contain parameters (or declarations, types, ...) that are not consistent with the way I am architecting this simple project. The datasource for the listbox comes from a class called ContactDB.  The ContactDB class also contains a method called "Delete" for removing a ContactModel object (firstName, LastName) from the listbox.  I am not able to wire up a Delete command for removing selected entries from the listbox.  Below is the code behind and the xaml for this proejct.  How can I modify this code so that I can use the Delete method from the ContactDB class?  Or should I maybe place the Delete method in the ContactViewModel class?

ContactDB.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace myMVVMexample4
{
    public static class ContactDb
    {
        private static List<ContactModel> _contacts = new List<ContactModel>();

        static ContactDb()
        {
            var jeremy = new ContactModel { FirstName = "Jeremy", LastName = "Likness", PhoneNumber = "404-555-1212" };
            var bill = new ContactModel { FirstName = "Bill", LastName = "Gates", PhoneNumber = "425-555-1212" };
            _contacts.Add(jeremy);
            _contacts.Add(bill);
        }

        public static IQueryable<ContactModel> GetContacts() { return _contacts.AsQueryable(); }

        public static void Delete(ContactModel contact)
        {
            if (_contacts.Contains(contact))
            {
                _contacts.Remove(contact);
            }
        }
    }
}


ContactModel.cs

using System;

namespace myMVVMexample4
{
    public class ContactModel
    {
        private string _firstName;

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                _firstName = value;
            }
        }

        private string _lastName;

        public string LastName
        {
            get { return _lastName; }
            set
            {
                _lastName = value;
            }
        }

        public string FullName
        {
            get { return string.Format("{0} {1}", FirstName, LastName); }
        }

        private string _phoneNumber;

        public string PhoneNumber
        {
            get { return _phoneNumber; }
            set
            {
                _phoneNumber = value;
            }
        }

    }
}

ContactViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;

namespace myMVVMexample4
{
    public class ContactViewModel : INotifyPropertyChanged
    {
        public ContactViewModel()
        {
            Contacts = new ObservableCollection<ContactModel>();
            GetContacts(_PopulateContacts);
        }

        private void _PopulateContacts(IEnumerable<ContactModel> contacts)
        {
            Contacts.Clear();
            foreach (var contact in contacts)
            {
                Contacts.Add(contact);
            }
        }

        public ObservableCollection<ContactModel> Contacts { get; set; }

        private ContactModel _currentContact;
        public ContactModel CurrentContact
        {
            get { return _currentContact; }
            set
            {
                _currentContact = value;
                RaisePropertyChanged("CurrentContact");
            }
        }

        public void GetContacts(Action<IQueryable<ContactModel>> callback)
        {
            callback(ContactDb.GetContacts());
        }

        private ICommand _DeleteCommand;
        public ICommand DeleteCommand
        {
            get
            {
                //--this code snippet causes the project to not load on startup
                //_DeleteCommand = new RelayCommand(DeleteAction(), _canDelete);
                return _DeleteCommand;
            }
        }

        public Action<ContactModel> DeleteAction()
        {
            return _DeleteAction;
        }

        private Action<ContactModel> _DeleteAction;
        private Func<bool> _canDelete;

        //-------------------------------------------------

        protected void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

MainWindow.xaml

<Window x:Class="myMVVMexample4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:VM="clr-namespace:myMVVMexample4"
        Title="MainWindow" Height="250" Width="375"><Window.DataContext><VM:ContactViewModel /></Window.DataContext><Grid x:Name="LayoutRoot" Background="LightBlue" ><Grid.RowDefinitions><RowDefinition Height="50*"/><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="200*"/><ColumnDefinition Width="140*"/></Grid.ColumnDefinitions><ListBox ItemsSource="{Binding Contacts}" DisplayMemberPath="FullName" SelectedItem="{Binding CurrentContact,Mode=TwoWay}" HorizontalAlignment="Left" Height="88" Margin="29,36,0,0" VerticalAlignment="Top" Width="211"/><Button Content=" Delete Selected " Command="{Binding DeleteCommand}" Grid.Column="2" HorizontalAlignment="Left" Height="39" Margin="22,41,0,0" VerticalAlignment="Top" Width="108"/></Grid></Window>


Rich P



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>