Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
public class Contact : BindableBase
    {
        private int id;
        private string name;
        private string address;
        private int number;
       
        [PrimaryKey] [AutoIncrement]
        public int Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
                OnPropertyChanged("Id");
            }
        }

        [MaxLength(56)]
        public string Name 
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
        
        [MaxLength(128)]
        public string Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
                OnPropertyChanged("Address");
            }
        }

        [MaxLength(15)]
        public int Number
        {
            get
            {
                return number;
            }
            set
            {
                number = value;
                OnPropertyChanged("Number");
            }
        }

    }


C#
class MainPageViewModel : BindableBase
    {
        private ObservableCollection<Contact> myContact;
        public ObservableCollection<Contact> MyContact
        {
            get
            {
                return myContact;
            }
            set
            {
                myContact = value;
                OnPropertyChanged("MyContact");
            }
        }

        public Contact addToMyContact { get; set; }
        public Contact selectedMyContact { get; set; }
        public Contact GetContactById(int Id)
        {
            using (var db = new SQLiteConnection(App.DbPath))
            {
                Contact m = (from p in db.Table<Contact>()
                            where p.Id == Id
                            select p).FirstOrDefault();
                return m;
            }
        }
        
        #region Adding Data 
        private ICommand addMyContact;
        public ICommand AddMyContact
        {
             get
            {
                if (null == addMyContact)
                    addMyContact = new Command<object>(addDataExecuteCommand);

                return addMyContact;
            }
        }
        private async void addDataExecuteCommand(object notused)
        {
            SQLiteAsyncConnection conn = new SQLiteAsyncConnection(App.DbPath);
            Contact contact = new Contact
            {
                Name = addToMyContact.Name,
                Address = addToMyContact.Address,
                Number = addToMyContact.Number,
                Id = addToMyContact.Id,

            };
            await conn.InsertAsync(contact);
            var line = new MessageDialog("Records Inserted");
            await line.ShowAsync();

        }
        #endregion

        #region Delete Selected Item
        private ICommand deleteSelected;
        public ICommand DeleteSelected
        {
            get
            {
                if (null == deleteSelected)
                    deleteSelected = new Command<object>(DeleteCommand);

                return deleteSelected;
            }
        }
        public void DeleteCommand(object notUsed)
        {
            if (selectedMyContact != null)
            {
                SQLiteAsyncConnection conn = new SQLiteAsyncConnection(App.DbPath);
                // Object model:
                conn.DeleteAsync(selectedMyContact);
            }
        }
        #endregion

        #region Delete All Data
        private ICommand deleteAll;
        public ICommand DeleteAll
        {
            get
            {
                if (null == deleteAll)
                    deleteAll = new Command<object>(DeleteCommand);

                return deleteAll;
            }
        }
        private async void DeleteAllCommand(object notused)
        {
            SQLiteAsyncConnection conn = new SQLiteAsyncConnection(App.DbPath);
            await conn.DropTableAsync<Contact>();
            
            MyContact.Clear();
                       
            var line = new MessageDialog("All Records Deleted");
            await line.ShowAsync();
        }
        #endregion

        #region Navigate To Edit Page

        private ICommand navigateToEditPage;
        public ICommand NavigateToEditPage
        {
            get
            {
                if (null == navigateToEditPage)
                    navigateToEditPage = new Command<object>(EditPageCommand);

                return navigateToEditPage;
            }
        }
        private void EditPageCommand(object notused)
        {
            if (selectedMyContact != null)
            {
                var rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(EditPage));

            }
        }
        #endregion

        #region Selected Item Edit And Update
        private ICommand update;
        public ICommand Update
        {
            get
            {
                if (null == update)
                    update = new Command<object>( UpdateCommand);

                return update;
            }
        }
        private void UpdateCommand(object notused)
        {

            var rootFrame = Window.Current.Content as Frame;
            rootFrame.Navigate(typeof(MainPage));

        }
        #endregion

        #region Listall Data

        //private ICommand listAllContact;
        private Command<Contact> listAllContact;
        public ICommand ListAllContact
        {
            get
            {
                if (null == listAllContact)
                    listAllContact = new Command<Contact>(listAllContactCommand);

                return listAllContact;
            }
        }

        private async void listAllContactCommand(Contact mylistContact)
        {
            SQLiteAsyncConnection conn = new SQLiteAsyncConnection(App.DbPath);
            
            var query = conn.Table<Contact>();
            var result = await query.ToListAsync();
            
            MessageDialog msg = new MessageDialog("Listing all Data");
            await msg.ShowAsync();

            
        }
        #endregion

        #region Constructs
        public MainPageViewModel()
        {

            addToMyContact = new Contact();
            selectedMyContact = new Contact();
            MyContact = new ObservableCollection<Contact>();
        }
        #endregion
        private static MainPageViewModel mainPageViewModel;
        public static MainPageViewModel GetInstance()
        {
            return mainPageViewModel ?? (mainPageViewModel = new MainPageViewModel());
        }
    }


C#
class Command<T> : ICommand
    {
        private readonly Action<T> _execute = null;
        private readonly Predicate<T> _canExecute = null;

        /// <summary>
        /// Raised when RaiseCanExecuteChanged is called.
        /// </summary>
        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// Creates a new command that can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public Command(Action<T> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public Command(Action<T> execute, Predicate<T> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }

        /// <summary>
        /// Determines whether this <see cref="RelayCommand"/> can execute in its current state.
        /// </summary>
        /// <param name="parameter">
        /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
        /// </param>
        /// <returns>true if this command can be executed; otherwise, false.</returns>
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute((T)parameter);
        }


        /// <summary>
        /// Executes the <see cref="RelayCommand"/> on the current command target.
        /// </summary>
        /// <param name="parameter">
        /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
        /// </param>
        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        /// <summary>
        /// Method used to raise the <see cref="CanExecuteChanged"/> event
        /// to indicate that the return value of the <see cref="CanExecute"/>
        /// method has changed.
        /// </summary>
        public void RaiseCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }


XML
<Page
    x:Class="Sql.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sql"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid removed="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView HorizontalAlignment="Left" Height="546" Margin="101,36,0,0" VerticalAlignment="Top" Width="662"
                  ItemsSource="{Binding MyContact, Mode=TwoWay}" SelectedItem="{Binding selectedMyContact , Mode=TwoWay}" 
                  SelectionMode="Single" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <StackPanel Width="400" removed="Chocolate">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Name, Mode=TwoWay}" FontSize="30" />
                            <TextBlock Text="," FontSize="30" />
                            <TextBlock Text="{Binding Number, Mode=TwoWay}" FontSize="30" />
                        </StackPanel>
                        <TextBlock Text="{Binding Address , Mode=TwoWay}" FontSize="30" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>



        <TextBlock Text="Name" FontSize="30" Margin="807,39,394,666" Height="63"/>
        <TextBox DataContext="{Binding addToMyContact}" Text="{Binding Name, Mode=TwoWay}" 
                 FontSize="30" Margin="1038,36,30,666"/>
        <TextBlock Text="Number" FontSize="30" Margin="807,157,357,548"/>
        <TextBox DataContext="{Binding addToMyContact}" Text="{Binding Number, Mode=TwoWay}" 
                 FontSize="30" Margin="1038,145,30,561"/>
        <TextBlock Text="Adress" FontSize="30" Margin="807,255,362,441"/>
        <TextBox DataContext="{Binding addToMyContact}" Text="{Binding Adress, Mode=TwoWay}" 
                 FontSize="30" Margin="1032,255,30,444"/>

        <Button Content="Add" VerticalAlignment="Top"
                Command="{Binding AddMyContact}" Margin="804,386,0,0" Width="175"/>
        <Button Content="Delete All" Command="{Binding DeleteAll}"
                HorizontalAlignment="Left" Margin="995,386,0,0" 
                VerticalAlignment="Top"/>
        <Button Content="Delete" Command="{Binding DeleteSelected}" 
                HorizontalAlignment="Left" Margin="1100,386,0,0" VerticalAlignment="Top"/>
        
        <Button Content="Delete All" Command="{Binding DeleteAll}" 
                HorizontalAlignment="Left" Margin="1100,386,0,0" VerticalAlignment="Top"/>
        
        <Button Content="List All" Command="{Binding DeleteAll}" 
                HorizontalAlignment="Left" Margin="804,467,0,0" VerticalAlignment="Top"/>

        <Button Content="Edit" Command="{Binding NavigateToEditPage, Source={Binding selectedMyContact}}" 
                HorizontalAlignment="Left" Margin="1195,386,0,0" VerticalAlignment="Top" Width="123"/>
        
        
    </Grid>
</Page>


C#
public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.DataContext = MainPageViewModel.GetInstance();
        }
    }


XML
<Page
    x:Class="Sql.View.EditPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Sql.View"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid removed="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Name" FontSize="30" Margin="807,39,394,666" Height="63"/>
        <TextBox Text="{Binding selectedMyContact.Name, Mode=TwoWay}"  FontSize="30" Margin="1038,36,30,666"/>
        <TextBlock Text="Adress" FontSize="30" Margin="807,157,357,548"/>
        <TextBox Text="{Binding selectedMyContact.Address, Mode=TwoWay}" FontSize="30" Margin="1038,145,30,561"/>
        <TextBlock Text="Number" FontSize="30" Margin="807,255,362,441"/>
        <TextBox Text="{Binding selectedMyContact.Number, Mode=TwoWay}" FontSize="30" Margin="1032,255,30,444" AcceptsReturn="True"/>

        <Button Content="Update" Command="{Binding Update}" 
                HorizontalAlignment="Left" Margin="804,473,0,0" VerticalAlignment="Top" Width="171"/>
    </Grid>
</Page>


C#
public sealed partial class EditPage : Page
    {
        public EditPage()
        {
            this.InitializeComponent();
            this.DataContext = MainPageViewModel.GetInstance();
        }
    }



how to display all data list View

this is correct form of MVVM

any way to reduce code
Posted
Updated 10-Jun-14 23:40pm
v2
Comments
ZurdoDev 11-Jun-14 21:10pm    
Please don't post this much code and expect people to go through it all. I realize you're asking for a way to reduce code but it is unlikely someone will go through all of this for you.
[no name] 12-Jun-14 4:24am    
how to display all data list View

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900