使用分页CollectionView的WPF可编辑DataGrid

时间:2014-08-16 22:17:53

标签: c# wpf datagrid

我正在按照此帖Pagination in WPF中的建议实现分页数据网格。一切正常,但我的网格中有一些复选框,当我尝试检查它们时,应用程序抛出异常,因为CollectionView不允许编辑。如何获取当前视图中的项目列表并将其转换为列表集合?我在public class PagingCollectionView : CollectionView类中添加了以下方法进行测试:

    private void RefreshGrid()
    {
        //this._currentDataGrid.DataContext = this;   **throws exception** when clicking on 
        //this.Refresh();                             **checkbox

        List<Customer> list = this.Cast<Customer>().ToList();  //** still get the original list
        this._currentDataGrid.DataContext = list;
        this.Refresh();

        //I also tried this
        //this.Refresh();
        //List<Customer> list = this.Cast<Customer>().ToList();  //** same result
        //this._currentDataGrid.DataContext = list;
    }

理想情况下,我想获取视图中的项目,此时我将每页的项目设置为5,但我得到了所有16项。 PagingCollectionView工作正常,但我无法检查框。

1 个答案:

答案 0 :(得分:3)

来自关联帖子的PagingCollectionView未实现IEditableCollectionView,因此您无法更改网格中的值。

不幸的是,WPF中似乎没有标准的分页集合视图。但是Silverlight的PagedCollectionView确实有效,只需将该代码复制到您的项目中即可。我想您也可以安装Silverlight SDK并添加对System.Windows.Data.dll的引用。或者,如果您可以自己实施IEditableCollectionView,我相信您会找到一些参与者;)。

对于看起来最合适的内容,您需要this page中的所有代码。

测试输出:

My test output

视图模型:

using System;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Windows.Input;

namespace WpfApplication1.ViewModels
{
    public class CustomersViewModel : NotifyBase // replace NotifyBase by implementing INotifyPropertyChanged
    {
        public PagedCollectionView CustomerCollection { get; private set; }
        public int TotalPages { get { return (int)Math.Ceiling((double)CustomerCollection.ItemCount / (double)CustomerCollection.PageSize); } }
        public int PageNumber { get { return CustomerCollection.PageIndex + 1; } } 

        public ICommand MoveNextCommand { get { return GetValue(() => MoveNextCommand); } set { SetValue(() => MoveNextCommand, value); } }
        public ICommand MovePreviousCommand { get { return GetValue(() => MovePreviousCommand); } set { SetValue(() => MovePreviousCommand, value); } }

        public CustomersViewModel()
        {
            this.CustomerCollection = new PagedCollectionView(new ObservableCollection<Customer>
            {
                new Customer(true, "Michael", "Delaney"),
                new Customer(false, "James", "Ferguson"),
                new Customer(false, "Andrew", "McDonnell"),
                new Customer(true, "Sammie", "Hunnery"),
                new Customer(true, "Olivia", "Tirolio"),
                new Customer(false, "Fran", "Rockwell"),
                new Customer(false, "Andrew", "Renard"),
            });
            this.CustomerCollection.PageSize = 3;

            this.MoveNextCommand = new ActionCommand(MoveNext);
            this.MovePreviousCommand = new ActionCommand(MovePrevious);

        }

        private void MoveNext()
        {
            this.CustomerCollection.MoveToNextPage();
            OnPropertyChanged("PageNumber");
        }

        private void MovePrevious()
        {
            this.CustomerCollection.MoveToPreviousPage();
            OnPropertyChanged("PageNumber");
        }
    }

    public class Customer : NotifyBase // replace NotifyBase by implementing INotifyPropertyChanged
    {
        public bool IsActive { get { return GetValue(() => IsActive); } set { SetValue(() => IsActive, value); } }
        public string FirstName { get { return GetValue(() => FirstName); } set { SetValue(() => FirstName, value); } }
        public string LastName { get { return GetValue(() => LastName); } set { SetValue(() => LastName, value); } }

        public Customer(bool isActive, string firstName, string lastName)
        {
            this.IsActive = isActive;
            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

    public class ActionCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        private Action _action;

        public ActionCommand(Action action)
        {
            _action = action;
        }

        public bool CanExecute(object parameter) { return true; }

        public void Execute(object parameter)
        {
            if (_action != null)
                _action();
        }
    }
}

Xaml(注意TemplateColumn而不是CheckBoxColumn,因为this)。

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:WpfApplication1.ViewModels"            
        Title="MainWindow" Height="350" Width="500">

    <Window.DataContext>
        <vm:CustomersViewModel />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0">
            <Button Content="Previous" Command="{Binding MovePreviousCommand}" Margin="2"/>
            <Button Content="Next" Command="{Binding MoveNextCommand}" Margin="2"/>
            <TextBlock Grid.Row="0" Margin="2" VerticalAlignment="Center" HorizontalAlignment="Right" DockPanel.Dock="Right">
                <TextBlock.Text>
                    <MultiBinding StringFormat="Page {0}/{1}">
                        <Binding Path="PageNumber" />
                        <Binding Path="TotalPages" />
                    </MultiBinding>
                </TextBlock.Text>
            </TextBlock>
        </DockPanel>
        <DataGrid ItemsSource="{Binding CustomerCollection}" Grid.Row="1">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Active">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox IsChecked="{Binding Path=IsActive, UpdateSourceTrigger=PropertyChanged}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn Header="First Name" Width="*" Binding="{Binding FirstName}"/>
                <DataGridTextColumn Header="Last Name" Width="*" Binding="{Binding LastName}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

版本管理似乎存在轻微问题(不会阻止代码工作),因此您可能想要评论PagedCollectionView.MoveNext中的前四行。

public bool MoveNext()
{
    //if (this._timestamp != this._collectionView.Timestamp)
    //{
    //    throw new InvalidOperationException(PagedCollectionViewResources.EnumeratorVersionChanged);
    //}

    switch (this._position)