wpf MVVM WPF中列表视图复选框的选定项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15051763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 07:41:43  来源:igfitidea点击:

Selected items of listview checkbox in MVVM WPF

wpflistviewmvvmlistviewitem

提问by Hussain

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

FormWeek.xaml 中的代码为

<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

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

我的视图模型 TaskWeek.cs 如下

//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.

下面是按钮单击 commond 以保存数据。

<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

现在我的要求是通过命令对象将选定的列表视图项传递到查看模型。我通过 SelectionChanged 事件在 FormWeek.xam.cs 中使用以下代码完成了此操作

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

但是请让我知道如何通过 MVVM 实现这个逻辑。如何在我的视图模型 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.

在研发和谷歌之后,我通过 RelayCommand 完成了更改。在 OnCheckBoxCommand 方法中,foreach 语句是错误的,它整天都在传递。我只想传递选定的列表视图项。请建议我 OnCheckBoxCommand 方法有什么问题。

采纳答案by Sunil


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


这是我的发现;
在 FormWeek.xaml 后面的代码中使用此代码:


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

And in 'OnCheckBoxCommand': -

在“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.

祝你有美好的一天……继续。

回答by yo chauhan

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.

我希望这会给你一个想法。