简体   繁体   中英

Using Update button in WPF ListView to update Selected Item

I have to make a WPF App to add, delete and update Items for Client Management purposes. I have so far been able to add and remove the items to the List using MVVM but I am unable to update the selected items. I require help in this regard. The code for the project is as follows:

Details Class.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace Assignment_2.Model
{
    public class Details :INotifyPropertyChanged
    {
        private string name;
        public string Name
        { get { return name; } set { name = value; OnPropertyChanged(Name); } }

        private string company;
        public string Company 
        { get { return company; } set { company = value; OnPropertyChanged(Company); } }  
        
        private string region;
        public string Region 
        { get { return region; } set { region = value; OnPropertyChanged(Region); } }


        private string hra;
        public string HRA
        {
            get { return hra; }
            set
            {
                hra = value;
                OnPropertyChanged(HRA);
            }
        }



        private string basic;
        public string Basic
        { get { return basic; } 
            set { basic = value;
                OnPropertyChanged(Basic);
            } 
        }

        private string pf;
        public string PF
        { get { return pf; } 
            set 
            { 
                pf = value;
                OnPropertyChanged(PF);
            } 
        }

        private string salary;
        public string Salary
        { get { return salary; } 
            set 
            { 
                salary = value;
                OnPropertyChanged(Salary);
            }
        }

       

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string det)
        {
            PropertyChangedEventHandler pc = PropertyChanged;
            if (pc != null)
                pc(this, new PropertyChangedEventArgs(det));
            
        }


       
    }
}

DetailsViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Assignment_2.Commands;
using Assignment_2.Model;

namespace Assignment_2.ViewModel
{
    public class DetailsViewModel : INotifyPropertyChanged
    {
        

        private Details record;
        public Details Record
        {
            get { return record; }
            set { record = value; NotifyPropertyChanged("Record"); }
        }
        private ObservableCollection<Details> records;
        public ObservableCollection<Details> Records
        {
            get { return records; }
            set { records = value; } //  NotifyPropertyChanged("Records");
        }


            
        private ICommand _SubmitCommand;
        public ICommand SubmitCommand
        {
            get
            {
                if (_SubmitCommand == null)
                {
                    _SubmitCommand = new RelayCommand(SubmitExecute, CanSubmitExecute, false);
                }
                return _SubmitCommand;
            }
        }

        public DetailsViewModel()
        {
            Record = new Details();
            Records = new ObservableCollection<Details>();
            
        }
         

        private void SubmitExecute(object parameter)
        {
            var TempRecord = new Details();
            //TempRecord = Record;

            TempRecord.Name = Record.Name;
            TempRecord.Company = Record.Company;
            TempRecord.Region = Record.Region;
            TempRecord.HRA = Record.HRA;
            TempRecord.Salary = Record.Salary;
            TempRecord.Basic = Record.Basic;
            TempRecord.PF = Record.PF;

            Records.Add(TempRecord);
        }
        
        private bool CanSubmitExecute(object parameter)
        {
            if (string.IsNullOrEmpty(Record.Name) || string.IsNullOrEmpty(Record.Company))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private ICommand _SubmitCommand1;
        public ICommand SubmitCommand1
        {
            get
            {
                if (_SubmitCommand1 == null)
                {
                    _SubmitCommand1 = new RelayCommand(SubmitExecute1, CanSubmitExecute1, false);
                }
                return _SubmitCommand1;
            }
        }

        public int findIndex(Details myDetails)
        {
            int count = 0;
            for (int i = 0; i < Records.Count; i++)
            {
                count = 0;
                Details myRecord = Records[i];
                if (myRecord.Name == myDetails.Name)
                    count++;
                else continue;
                if (myRecord.Company == myDetails.Company)
                    count++;
                else continue;
                
                if (myRecord.Region == myDetails.Region)
                    count++;
                else continue;
                if (myRecord.Salary == myDetails.Salary)
                    count++;
                else continue;
                if (myRecord.HRA == myDetails.HRA)
                    count++;
                else continue;
                if (myRecord.Basic == myDetails.Basic)
                    count++;
                else continue;
                if (myRecord.PF == myDetails.PF)
                    count++;
                else continue;

                if (count == 7)
                    return i;
            }
            return -1;


        }

        private void SubmitExecute1(object parameter)
        {
            Records.Remove((Details)parameter);

        }
        private bool CanSubmitExecute1(object parameter)
        {
            if (string.IsNullOrEmpty(Record.Name) || string.IsNullOrEmpty(Record.Company))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private ICommand _SubmitCommand2;
        public ICommand SubmitCommand2
        {
            get
            {
                if (_SubmitCommand2 == null)
                {
                    _SubmitCommand2 = new RelayCommand(SubmitExecute2, CanSubmitExecute2, false);
                }
                return _SubmitCommand2;
            }
        }


        private void SubmitExecute2(object parameter)
        {
            
            

        }
        private bool CanSubmitExecute2(object parameter)
        {
            if (string.IsNullOrEmpty(Record.Name) || string.IsNullOrEmpty(Record.Company))
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        protected void NotifyPropertyChanged(string de)
        {
            
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(de));

        }

       


    
     }
}

RelayCommand.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Assignment_2.Commands
{
    class RelayCommand : ICommand
    {
        Action<object> executeAction;
        Func<object, bool> canExecute;
        bool canExecuteCache;


        public RelayCommand(Action<object> executeAction, Func<object, bool> canExecute, bool canExecuteCache)
        {
            this.canExecute = canExecute;
            this.executeAction = executeAction;
            canExecuteCache = canExecuteCache;
        }

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;

            }
            else
            {
                return canExecute(parameter);
            }
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {

                CommandManager.RequerySuggested += value;

            }
            remove
            {

                CommandManager.RequerySuggested -= value;

            }
        }

        public void Execute(object parameter)
        {
            executeAction(parameter);
        }
    }
}

MainWindow.xaml

<Window x:Class="Assignment_2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:vm="clr-namespace:Assignment_2.ViewModel"  

        Title="MainWindow" Height="401" Width="472">

    <Window.Resources>
        <vm:DetailsViewModel x:Key="DetailsViewModel"/>

    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource DetailsViewModel}}" RenderTransformOrigin="0.5,0.5" Margin="0,0,1,1">
        <Grid.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="-0.21"/>
                <TranslateTransform/>
            </TransformGroup>
        </Grid.RenderTransform>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="20.59"/>
            <RowDefinition Height="22.906"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="29*"/>
            <RowDefinition Height="293*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Text=" Name" HorizontalAlignment="Center" Margin="0,0,0,4" Grid.RowSpan="2" Width="35" />
        <TextBox Grid.Column="1" Width="100" HorizontalAlignment="Left" Text="{Binding Record.Name,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Margin="2,0,0,1" Grid.RowSpan="2"/>
        <TextBlock Text="Company" HorizontalAlignment="Center" Margin="0,2,0,3" Width="51" Grid.RowSpan="2" Grid.Row="1"/>
        <TextBox Grid.Column="1" Width="100" HorizontalAlignment="Left" Text="{Binding Record.Company,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="2,2,0,1" Grid.Row="1"/>
        <TextBlock Grid.Row="2" Text="Region" HorizontalAlignment="Center" Margin="0,1,0,4" Width="37"/>
        <TextBox Grid.Row="2" Grid.Column="1" Width="100" HorizontalAlignment="Left" Text="{Binding Record.Region,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="3,1,0,4"/>
        <TextBlock Grid.Column="1" Text="HRA" HorizontalAlignment="Left" Margin="131,-1,0,2" Width="23"/>
        <TextBox Grid.Column="1" Width="83" HorizontalAlignment="Left" Text="{Binding Record.HRA,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="162,0,0,1"/>
        <TextBlock Grid.Column="1" Text="Basic" HorizontalAlignment="Left" Margin="129,2,0,13" Width="26" Grid.RowSpan="2" Grid.Row="1"/>
        <TextBox Grid.Column="1" Width="81" HorizontalAlignment="Left" Text="{Binding Record.Basic,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="162,2,0,3" Grid.Row="1"/>
        <TextBlock Grid.Row="2" Grid.Column="1" Text="PF" HorizontalAlignment="Left" Margin="144,1,0,5" Width="12"/>
        <TextBox Grid.Row="2" Grid.Column="1" Width="100" HorizontalAlignment="Left" Text="{Binding Record.PF,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="162,2,0,1"/>
        <TextBlock Grid.Column="1" Text="Salary" HorizontalAlignment="Left" Margin="268,-1,0,1" Width="36"/>
        <TextBox Grid.Column="1" Width="100" HorizontalAlignment="Left" Text="{Binding Record.Salary,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Margin="304,0,0,21" Grid.RowSpan="2"/>
        <Button Content="Add" Command="{Binding SubmitCommand }" HorizontalAlignment="Left" Grid.Row="4" Margin="121,4,0,5" Width="44" Grid.Column="1"/>



        <ListView x:Name="ListedView" ItemsSource="{Binding Records}" Width="Auto" Grid.Row="5" Margin="38,3,13,36" Grid.ColumnSpan="2">

            <ListView.View >

                <GridView >
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="Auto" />
                    <GridViewColumn  Header="Company" DisplayMemberBinding="{Binding Company}" Width="Auto"/>
                    <GridViewColumn  Header="Region" DisplayMemberBinding="{Binding Region}" Width="Auto" />
                    <GridViewColumn  Header="HRA" DisplayMemberBinding="{Binding HRA}" Width="Auto" />
                    <GridViewColumn  Header="Basic" DisplayMemberBinding="{Binding Basic}" Width="Auto" />
                    <GridViewColumn  Header="PF" DisplayMemberBinding="{Binding PF}" Width="Auto" />
                    <GridViewColumn  Header="Salary" DisplayMemberBinding="{Binding Salary}" Width="Auto" />
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Remove" Margin="1,36,50,150" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView},Path=DataContext.SubmitCommand1}"/>

                              
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

Any help is appreciated in this regard. Thanks

If I understand your issue correctly, you should bind the SelectedItem property of the ListView to be able to edit the currently selected item in the TextBox elements above the ListView :

<ListView SelectedItem="{Binding Record}" ... />

With or without Binding you can do it like this:

if ((sender as ListView).SelectedValue != null)
   {
       string item = (sender as ListView).SelectedValue.ToString();
       SelectedIndex = (sender as ListView).SelectedIndex;
       list.Items[SelectedIndex] = "Updated";
   }

(I like to add a ContextMenu on my ListViewItems so it is easier for users to modify the specified clicked item):

<ListView x:Name="list">
   <ListView.ContextMenu>
      <ContextMenu x:Name="contextmenu">
         <MenuItem x:Name="Add" Header="Add" Click="Add_Click"/>
         <MenuItem x:Name="Del" Header="Delete" Click="Del_Click"/>
         <MenuItem x:Name="Update" Header="Update" Click="Update_Click"/>
       </ContextMenu>
   </ListView.ContextMenu>
</ListView>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM