WPF MVVM:用于选择/取消选择所有列表视图项的列表视图复选框标题

问题描述:

当我单击列表视图标题中的复选框时,我试图选择/取消选择所有列表视图项目.

I am trying to select/unselect all the listview items when checkbox in listview header is clicked.

查看(xaml):

            <ListView Margin="10" Name="MyLv" ItemsSource="Binding Path=lstData}" SelectionMode="Extended">
                <ListView.ItemContainerStyle>
                    <Style TargetType="ListViewItem">
                        <Setter Property="IsSelected" Value="{Binding IsSelected}"/>
                    </Style>
                </ListView.ItemContainerStyle>
                <ListView.View>
                    <GridView>
                        <!-- Checkbox column -->
                        <GridViewColumn>
                            <GridViewColumn.Header>
                                <CheckBox x:Name="CheckAll" Command="{Binding CheckAllCommand}" 
                                          CommandParameter="{Binding IsChecked, ElementName=CheckAll}" />
                            </GridViewColumn.Header>
                            <GridViewColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <CheckBox IsChecked="{Binding IsSelected}" />
                                    </StackPanel>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                        <GridViewColumn Header="ID" Width="120" DisplayMemberBinding="{Binding ID}" />
                        <GridViewColumn Header="Desc" Width="50" DisplayMemberBinding="{Binding Desc}" />
                    </GridView>
                </ListView.View>
            </ListView>

代码隐藏构造函数(xaml.cs):

    public MyView()           
    {
        DataContext = new MyViewModel();
        InitializeComponent();
    }

ViewModel :

    public  ObservableCollection<DataModel> lstData = null;
    public MyViewModel()
    {          
        this.lstData = this.LoadData();  // this connects to a database an extract info to be loaded in listview
    }

    private RelayCommand checkAllCommand;
    public ICommand CheckAllCommand
    {
        get
        {
            return checkAllCommand ??
                (checkAllCommand = new RelayCommand(param => this.SelectUnselectAll(Convert.ToBoolean(param.ToString()))));
        }
    }

    private void SelectUnselectAll(bool isSelected)
    {
        for (int i = 0; i < this.lstData.Count; i++)
        {
            this.lstData[i].IsSelected = isSelected;
        }
    }

数据模型:

public class DataModel
{
    public bool IsSelected { get; set; }
    public string ID { get; set; }
    public string Desc { get; set; }     
}

RelayCommand类:

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

我的问题如下:当我选中/取消选中列表视图标题中的复选框时,每个列表视图项的列表视图中的IsSelected列都不会更新.我想要以下行为:

My problem is the following: When I check/uncheck the checkbox in listview header, IsSelected column in listview for each listviewitem is not updated. I want the following behaviour:

  • 如果我选中列表视图标题中的复选框,则会选中所有列表视图项.
  • 如果我取消选中列表视图标题中的复选框,则所有列表视图项都将被取消选中.

您的类DataModel必须实现INotifyPropertyChanged,并在IsSelected属性更改时触发PropertyChanged事件.否则,不会通知ListViewItem的IsSelected属性的绑定.

Your class DataModel must implement INotifyPropertyChanged, and fire the PropertyChanged event when the IsSelected property changes. Otherwise, the Binding of the ListViewItem's IsSelected property isn't notified.

public class DataModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isSelected;
    public bool IsSelected
    {
        get { return isSelected; }
        set
        {
            isSelected = value;
            PropertyChanged?.Invoke(this,
                new PropertyChangedEventArgs(nameof(IsSelected)));
        }
    }

    public string ID { get; set; }
    public string Desc { get; set; }
}