3

我想在视图模型中传递列表视图复选框的选定项目,稍后我将使用进一步的过程存储在数据库中。

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);

        }

我的视图模型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" >

现在我的要求是通过命令对象将选定的列表视图项传递给视图模型。我通过 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 来实现这个逻辑。如何在我的视图模型 TaskWeek.cs 中获取选定项目

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

4

2 回答 2

1

嗨试试这样

   <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();
    }

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

于 2013-02-24T13:04:45.703 回答
1


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


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

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

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

于 2013-03-03T17:32:43.827 回答