Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected items of listview checkbox in MVVM WPF

I want to pass selected items of listview checkbox in view model, later I will use further process to store in database.

Code in the FormWeek.xaml as

<Window.DataContext>
        <Binding Source="{StaticResource Locator}" Path="TaskExecDefModel"></Binding>
    </Window.DataContext>
    <Window.Resources>
        <ResourceDictionary>
    <DataTemplate x:Key="ItemDataTemplate">
                    <CheckBox
                x:Name="checkbox"
                Content="{Binding}" Command="{Binding CheckBoxCommand}" CommandParameter="{Binding ElementName=checkedListView, Path=SelectedItems}"                    
                IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
                </DataTemplate>
</ResourceDictionary>

    <StackPanel Grid.Column="1" Grid.Row="3" Margin="5">
                    <CheckBox x:Name="selectAll" Content="Select all" Click="OnSelectAllChanged"/>            

<ListView x:Name="checkedListView" SelectionMode="Multiple" ItemsSource="{Binding CollectionOfDays}"  DataContext="{Binding}"
                      ItemTemplate="{StaticResource ItemDataTemplate}" SelectedValue="WorkingDay"
                      CheckBox.Unchecked="OnUncheckItem" SelectionChanged="SelectDays" SelectedItem="{Binding SelectedItems}">                    
            </ListView>

    </StackPanel>

Code in FormWeek.xaml.cs

 private void SelectDays(object sender, SelectionChangedEventArgs e)
        {
            (this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);

        }

My View Model TaskWeek.cs as follows

//Declaration

private RelayCommand<object> _checkBoxCommand;

public ObservableCollection<string> CollectionOfDays { get; set; }
public ObservableCollection<string> SelectedItems { get; set; }

 public RelayCommand<object> CheckBoxCommand
        {
            get
            {              
                if (_checkBoxCommand == null)
                {
                    _checkBoxCommand = new RelayCommand<object>((args) => OnCheckBoxCommand(args,true));
                  //  _checkBoxCommand = new RelayCommand(() => OnCheckBoxCommand(object args));
                }
                return _checkBoxCommand;
            }
        } 

//Constructor

CollectionOfDays = new ObservableCollection<string>();

//Method

private void GetWeekDays()
        {
            try
            {
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                    {

                        CollectionOfDays.Add("Saturday");
                        CollectionOfDays.Add("Sunday");
                        CollectionOfDays.Add("Monday");
                        CollectionOfDays.Add("Tuesday");
                        CollectionOfDays.Add("Wednesday");
                        CollectionOfDays.Add("Thursday");
                        CollectionOfDays.Add("Friday");                        
                    }));
            }
            catch(Exception Ex)
            {
                MessageBox.Show(Ex.Message, "TaskWeek:GetWeekDays");
            }
        }

public void OnCheckBoxCommand(object obj, bool _direction)
        {
            try
            {

                if (SelectedItems == null)
                    SelectedItems = new ObservableCollection<string>();

                if (obj != null)
                {
                    SelectedItems.Clear();
                    StringBuilder items = new StringBuilder();


                   if (_direction)
                    {
                        foreach (string item in CollectionOfDays)
                        {

                            items.AppendFormat(item + ",");
                        }
                    }

                    MessageBox.Show(items.ToString());
                   }
                else
                    SelectedItems.Clear();              

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "TaskDefinition:OnCheckBoxCommand");
            }
        }

And below is button click commond to save the data.

<Button Grid.Column="2" Grid.Row="2" Content="Save" HorizontalAlignment="Center" VerticalAlignment="Bottom" 
                Command="{Binding InsertExecDefCommand}"   Margin="5" >

Now my requirement is to pass selected listview items to view model through command object. I had done this using following code in FormWeek.xam.cs through SelectionChanged event as

private void OnSelectedItems(object sender, RoutedEventArgs e)
        {
            StringBuilder items = new StringBuilder();
            foreach (string item in checkedListView.SelectedItems)
            {
                items.AppendFormat(item + ",");
            }
            string AllDays= items.ToString();
        }

But please let me know how to achieve this logic through MVVM. How to get selecteditems in my view model TaskWeek.cs

After R&D and google i had done chages through RelayCommand. In OnCheckBoxCommand method foreach statement is wrong it is passing all days. I want to pass only selected listview item. Please suggest me what is wrong in OnCheckBoxCommand method.

like image 240
Hussain Avatar asked Dec 18 '25 18:12

Hussain


2 Answers


Here are my findings;
use this code in code behind of FormWeek.xaml:


    private void SelectDays(object sender, SelectionChangedEventArgs e)
    {
    (this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);
    }

And in 'OnCheckBoxCommand': -

 public void OnCheckBoxCommand(object obj, bool _direction)
    {
        try
        {
            if (SelectedItems == null) SelectedItems = new ObservableCollection<string>();

            if (obj != null)
            {
              SelectedItems.Clear(); 
              var _list = ((IList)obj).Cast<string>().ToList();   
              if (_direction)
              {
                 _list.ForEach(item => SelectedItems.Add(item));
              }
            }
            else
             SelectedItems.Clear();                           
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "TaskDefinition:OnCheckBoxCommand");
        }
}

Have a nice day man.....keep going.

like image 194
Sunil Avatar answered Dec 20 '25 10:12

Sunil


Hi try something like this

   <StackPanel Grid.Column="1" Grid.Row="3" Margin="5">
    <CheckBox x:Name="selectAll" Content="Select all" Command="{Binding CheckBoxCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Mode=Self}}"/>
    <ListView x:Name="checkedListView" SelectionMode="Extended"  ItemsSource="{Binding CollectionOfDays}" SelectedItem="{Binding SelectedItems}"/>
</StackPanel>

public class MainViewModel
{
    public MainViewModel()
    {
        CollectionOfDays = new ObservableCollection<string>();
        SelectedItems = new ObservableCollection<string>();

        CollectionOfDays.Add("Saturday");
        CollectionOfDays.Add("Sunday");
        CollectionOfDays.Add("Monday");
        CollectionOfDays.Add("Tuesday");
        CollectionOfDays.Add("Wednesday");
        CollectionOfDays.Add("Thursday");
        CollectionOfDays.Add("Friday");
    }

    private CommandHandler _checkBoxCommand;

    public CommandHandler CheckBoxCommand
    {
        get
        {
            return _checkBoxCommand ?? (_checkBoxCommand=new CommandHandler((param)=>OnCheckBoxCommand(param)));
        }
    }

    public ObservableCollection<string> CollectionOfDays { get; set; }

    public ObservableCollection<string> SelectedItems {get;set;}

    private void OnCheckBoxCommand(object obj)
    {

        if (obj is bool)
        {
            if (SelectedItems == null)
                SelectedItems = new ObservableCollection<string>();

            if ((bool)obj)
            {
                SelectedItems.Clear();
                foreach (var item in CollectionOfDays)
                {
                    SelectedItems.Add(item);
                }
            }
            else
                SelectedItems.Clear();
        }
    }

}

public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }

I hope this will give you an idea.

like image 45
yo chauhan Avatar answered Dec 20 '25 11:12

yo chauhan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!