我想在 View 模型中传递listview复选框的选定项,稍后我将使用进一步的过程来存储在数据库中。

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>

FormWeek.xaml.cs中的代码
 private void SelectDays(object sender, SelectionChangedEventArgs e)
        {
            (this.DataContext as TaskExecDefinitionViewModel).OnCheckBoxCommand(checkedListView.SelectedItems,true);

        }

我的 View 模型TaskWeek.cs如下

//宣言
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;
            }
        }

//构造函数
CollectionOfDays = new ObservableCollection<string>();

//方法
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");
            }
        }

下面是单击通用按钮以保存数据。
<Button Grid.Column="2" Grid.Row="2" Content="Save" HorizontalAlignment="Center" VerticalAlignment="Bottom"
                Command="{Binding InsertExecDefCommand}"   Margin="5" >

现在,我的要求是通过命令对象传递选定的listview项目以查看模型。我已经通过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();
        }

但是,请让我知道如何通过MVVM实现此逻辑。如何在我的 View 模型TaskWeek.cs中获取selecteditems

在研发和Google之后,我通过RelayCommand进行了改进。在OnCheckBoxCommand方法中,foreach语句是错误的,它整天都在传递。我只想传递所选的listview项目。请建议我OnCheckBoxCommand方法出了什么问题。

最佳答案

这是我的发现;

在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");
        }
}

祝你有美好的一天.....继续前进。

10-08 14:07