How to Iterate listview items using MVMV

Sarah 186 Reputation points
2022-05-21T18:48:16.48+00:00

Can someone help and show me how to iterate ListView items using MVVM?

In the Code Behind it is done as follows:

for (int i = 0; i < NameOfListView.Items.Count; i++)
{
//code
}

In MVVM unfortunately I don't know how to address the ListView.
The goal is to iterate over all items/rows and store the content in a list.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Hui Liu-MSFT 37,946 Reputation points Microsoft Vendor
    2022-05-23T06:24:59.65+00:00

    I'm not sure what kind of iteration effect you want. You could take a look at the example below. Any questions please let me know.
    MainWindow.xaml:

     <StackPanel>  
            <ListView x:Name="MColumnsListXaml" HorizontalAlignment="Left"    
                      Height="Auto" Margin="0,42,0,0" VerticalAlignment="Top"    
                      Width="Auto" ItemsSource="{Binding MColumnsList}">  
                <ListView.View>  
                    <GridView>  
                        <GridViewColumn Header="First Name" Width="Auto" DisplayMemberBinding="{Binding MColumnName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />  
                        <GridViewColumn Header="Last Name" Width="Auto" DisplayMemberBinding="{Binding MColumnName2,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />  
                    </GridView>  
                </ListView.View>  
            </ListView>  
            <Button x:Name="btn" Content="load" Width="100" Height="40" Click="btn_Click" />  
            <TextBlock x:Name="tb"  Width="100" Height="40"  />  
            <DataGrid x:Name="dg"  />  
        </StackPanel>  
    

    MainWindow.xaml.cs:

    using System.Collections.ObjectModel;  
    using System.ComponentModel;  
    using System.Runtime.CompilerServices;  
    using System.Windows;  
      
    namespace ListViewIterate  
    {  
      public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
          DataContext =new ViewModel();  
        }  
        public ObservableCollection<MandatoryColumns> DGItems;  
        public void test()  
        {  
           ObservableCollection<MandatoryColumns> items = (ObservableCollection<MandatoryColumns>)MColumnsListXaml.ItemsSource;  
       
      foreach (var item in items)  
      {  
        DGItems = new ObservableCollection<MandatoryColumns>();  
        
        item.MColumnName="item";  
        DGItems.Add(item);  
        tb.Text = item.ToString();  
    
      }  
      dg.ItemsSource = items;  
        }  
      
        private void btn_Click(object sender, RoutedEventArgs e)  
        {  
          test();  
        }  
      }  
      public class ViewModel : INotifyPropertyChanged  
      {  
        private ObservableCollection<MandatoryColumns> mColumnsList;  
        public ObservableCollection<MandatoryColumns> MColumnsList  
        {  
          get { return mColumnsList;}  
          set { mColumnsList=value; OnPropertyChanged("MColumnsList");}  
        }  
        public ViewModel()  
        {  
           MColumnsList = new ObservableCollection<MandatoryColumns>();  
          MColumnsList.Add(new MandatoryColumns() { MColumnName = "John", MColumnName2 = "Smith" });  
          MColumnsList.Add(new MandatoryColumns() { MColumnName = "Jason", MColumnName2 = "Bell" });  
          MColumnsList.Add(new MandatoryColumns() { MColumnName = "Jason1", MColumnName2 = "Bell2" });  
           
        }  
        public event PropertyChangedEventHandler PropertyChanged;  
        protected void OnPropertyChanged([CallerMemberName] string name = null)  
        {  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));  
        }  
      }  
      public class MandatoryColumns  
      {  
        public string MColumnName { get; set; }  
        public string MColumnName2 { get; set; }  
      
        public override string ToString()  
        {  
          return (MColumnName + "--"+MColumnName2) .ToString();  
        }  
      }  
    }  
    

    Update:
    MainWindow.xaml:

    <Window.DataContext>  
            <local:ViewModel/>  
        </Window.DataContext>  
        <StackPanel>  
            <ListView  ItemsSource="{Binding View}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}">  
                <ListView.View>  
                    <GridView AllowsColumnReorder="False">  
                        <GridViewColumn Header="CLM1">  
                            <GridViewColumn.CellTemplate>  
                                <DataTemplate>  
                                    <TextBlock Text="{Binding Cont1, UpdateSourceTrigger=PropertyChanged}"   
                                               TextWrapping="Wrap"/>  
                                </DataTemplate>  
                            </GridViewColumn.CellTemplate>  
                        </GridViewColumn>  
      
                        <GridViewColumn Header="CLM2">  
                            <GridViewColumn.CellTemplate>  
                                <DataTemplate>  
                                    <TextBox Text="{Binding Cont2, UpdateSourceTrigger=PropertyChanged}"  
                                             TextWrapping="Wrap"  
                                             Width="100"/>  
                                </DataTemplate>  
                            </GridViewColumn.CellTemplate>  
                        </GridViewColumn>  
      
                        <GridViewColumn Header="CLM3">  
                            <GridViewColumn.CellTemplate>  
                                <DataTemplate>  
                                    <TextBox Text="{Binding Cont3, UpdateSourceTrigger=PropertyChanged}"  
                                             TextWrapping="Wrap"  
                                             Width="100"/>  
                                </DataTemplate>  
                            </GridViewColumn.CellTemplate>  
                        </GridViewColumn>  
                    </GridView>  
                </ListView.View>  
            </ListView>  
            <Button Content="Add Item" Command="{Binding CmdSaveNew}" Width="150" Margin="5"/>  
            <Button Content="Delete Item" Command="{Binding CmdDelete}" Width="150" Margin="5"/>  
            <Button Content="Iterate"  
                    Width="70"  
                    Height="50"  
                    Command="{Binding Cmd}"  
                    CommandParameter="Iterate"/>  
            <ListView   x:Name="output" ItemsSource="{Binding Output}"   >  
                <ListView.ItemsPanel>  
                    <ItemsPanelTemplate>  
                        <StackPanel Orientation="Horizontal"></StackPanel>  
                    </ItemsPanelTemplate>  
                </ListView.ItemsPanel>  
            </ListView>  
        </StackPanel>  
    

    MainWindow.xaml.cs:

    public class ViewModel : INotifyPropertyChanged  
      {  
        private CollectionViewSource cvs = new CollectionViewSource();  
        public ICollectionView View  
        {  
          get  
          {  
            cvs.Source = InitImput();  
            return cvs.View;  
          }  
        }  
        public ViewModel()  
        {  
          CmdSaveNew = new RelayCommand(SaveNew);  
          CmdDelete = new RelayCommand(DeleteItem);  
        }  
         int id=5;  
        public void SaveNew(object parameter)  
        {  
          if (!string.IsNullOrEmpty("x"))   
          {  
            Model cat = new Model();  
            cat.Cont1 = $"{id}";   
            cat.Cont2 = "";   
            cat.Cont3 = "";   
              Input.Add(cat);  
            MessageBox.Show("success");  
            id+=1;  
          }  
          else  
          {  
            MessageBox.Show("error");  
          }  
        }  
        public void DeleteItem(object parameter)  
        {  
          if (SelectedItem != null)  
          {  
            Input.Remove(SelectedItem);  
          }  
        }  
        public ICommand Cmd { get => new RelayCommand(CmdExec); }  
        public ICommand CmdSaveNew { get; set; }  
        public ICommand CmdDelete { get; set; }  
      
        private void CmdExec(object parameter)  
        {  
          switch (parameter.ToString())  
          {  
            case "Iterate":  
      
              for (int i = 0; i < Input.Count; i++)  
              {  
                Output.Add(Input[i]);  
              }  
      
              MessageBox.Show("Items Added");  
              break;  
      
            default:  
              break;  
          }  
        }  
        private Model _selectedItem;  
        public Model SelectedItem  
        {  
          get { return _selectedItem; }  
          set  
          {  
            _selectedItem = value;  
            OnPropertyChanged("SelectedItem");  
          }  
        }  
        private ObservableCollection<Model> output = new ObservableCollection<Model>();  
        public ObservableCollection<Model> Output { get { return output;}set{ output=value;OnPropertyChanged("Output");} }   
      
      
        public event PropertyChangedEventHandler PropertyChanged;  
        protected void OnPropertyChanged([CallerMemberName] string name = null)  
        {  
          PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));  
        }  
      
        ObservableCollection<Model> Input = new ObservableCollection<Model>();  
        public ObservableCollection<Model> InitImput()  
        {  
          Input.Add(new Model() { Cont1 = "1", Cont2 = "A", Cont3 = "a" });  
          Input.Add(new Model() { Cont1 = "2", Cont2 = "B", Cont3 = "b" });  
          Input.Add(new Model() { Cont1 = "3", Cont2 = "C", Cont3 = "c" });  
          Input.Add(new Model() { Cont1 = "4", Cont2 = "D", Cont3 = "d" });  
      
          return Input;  
        }  
      
      }  
      
      public class Model  
      {  
        public string Cont1 { get; set; }  
        public string Cont2 { get; set; }  
        public string Cont3 { get; set; }  
        public override string ToString()  
        {  
          return Cont1+ Cont2+ Cont3 .ToString();  
        }  
      }  
      
      public class RelayCommand : ICommand  
      {  
        private readonly Predicate<object> _canExecute;  
        private readonly Action<object> _action;  
        public RelayCommand(Action<object> action) : this(action, null) { }  
        public RelayCommand(Action<object> action, Predicate<object> canExecute) { _action = action; _canExecute = canExecute; }  
        public void Execute(object o) => _action(o);  
        public bool CanExecute(object o) => _canExecute == null ? true : _canExecute(o);  
        public event EventHandler CanExecuteChanged  
        {  
          add { CommandManager.RequerySuggested += value; }  
          remove { CommandManager.RequerySuggested -= value; }  
        }  
      }  
    

    The result:
    205319-88.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Peter Fleischer (former MVP) 19,231 Reputation points
    2022-05-29T04:43:28.857+00:00

    Hi Sarah,
    the simplest way is to use Input for Add to Output because Input is binded to ListView and reflect all Items in LIstView:

    public ICommand Cmd { get => new RelayCommand(CmdExec); }
    private void CmdExec(object parameter)
    {
      switch (parameter.ToString())
      {
        case "Iterate":
          for (int i = 0; i < Input.Count; i++) Output.Add(Input[i]);
          MessageBox.Show("Items Added");
          break;
        default:
          break;
      }
    }
    
    0 comments No comments