在WPF中分组

时间:2012-09-09 19:39:40

标签: c# wpf datagrid grouping

我正在尝试修改现有的代码,允许按行添加文章并在需要的地方删除它们,问题是我正在尝试找到一种方法来对同一类别的文章进行分组。因此,当用户添加DVD类别的新文章时,它将直接添加到该类别中(我试图从这里获取一些想法,但没有成功:http://msdn.microsoft.com/en-us/library/ff407126.aspx

这是数据背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace WpfDataGridWithDataTable
{
    public class Article
    {
        public  Article ()
        {

        }
        private int  _modelNumber;
        public int ModelNumber
        {
            get { return _modelNumber; }
            set { _modelNumber = value; OnPropertyChanged("ModelNumber"); }
        }

        private string _modelName;
        public string ModelName
        {
            get { return _modelName; }
            set { _modelName = value; OnPropertyChanged("ModelName"); }
        }

        private decimal  _unitCost;
        public decimal UnitCost
        {
            get { return _unitCost; }
            set { _unitCost = value; OnPropertyChanged("UnitCost"); }
        }

        private string  _description ;
        public string Description
        {
            get { return _description; }
            set { _description = value; OnPropertyChanged("Description"); }
        }


        #region INotifyPropertyChanged Membres

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion
    }
    public class ListArticles : ObservableCollection<Article > 
    {
        public Article a;
        public ListArticles()
        {

                a = new Article();
                this.Add(a);

        }

    }

}

这是XAML代码:

<Window x:Class="WpfDataGridWithDataTable.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfDataGridWithDataTable"
        Title="Window1" Height="300" Width="300">
    <Grid
        Name="gridPanel">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <DataGrid 
            Grid.Column="0"
            Name="dataGrid1"  
            AutoGenerateColumns="True"  
            CanUserAddRows="True" 
            CanUserDeleteRows="True"
            CanUserResizeColumns="True"
            IsSynchronizedWithCurrentItem="True"
            ItemsSource="{Binding}"/>
        <ListBox 
            Grid.Column="1"
            Name="listBox1" 
            IsSynchronizedWithCurrentItem="True"
            ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type local:Article}">
                    <StackPanel    
                        Orientation="Horizontal">
                        <TextBlock 
                            Width="100"
                            Margin="10"  
                            Background="DarkBlue"
                            Foreground="White"
                            FontSize="14"
                            Text="{Binding ModelNumber}"/>
                        <TextBlock 
                            Width="100"
                            Margin="10" 
                            Background="DarkBlue"
                            Foreground="White"
                            FontSize="14"
                            Text="{Binding ModelName}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
            <Button 
                Grid.Row="1"
                Grid.Column="0"
                HorizontalAlignment="Left"
                Width="100"
                Name="btnAdd"
                Content="Add Item"
                Click="btnAdd_Click">
            </Button>
            <Button
                Grid.Row="1"
                Grid.Column="1"
                HorizontalAlignment="Right"
                Width="100"
                Name="btnDelete"
                Content="Delete Item"
                Click="btnDelete_Click" >
            </Button>
    </Grid>
</Window>

表格背后的代码:

namespace WpfDataGridWithDataTable
{
    /// <summary>
    /// Logique d'interaction pour Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        private ListArticles myList;
        public Window1()
        {
            InitializeComponent();
            myList = new ListArticles();


            this.DataContext = myList;

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            myList.Add(new Article());
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            myList.Remove(this.dataGrid1.SelectedItem as Article);
        }

    }
}

感谢您的回答。

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题,但我不知道为什么它没有用。将datagrid与CollectionViewSource绑定时,问题位于XAML代码中。我说:

 <DataGrid Name="dataGrid1"  
            AutoGenerateColumns="True"  
            CanUserAddRows="True" 
            CanUserDeleteRows="True"
            CanUserResizeColumns="True"
            IsSynchronizedWithCurrentItem="True"
            Grid.ColumnSpan="2" 
            ItemsSource="{Binding Source={StaticResource cvsListArticles}}">

最后一行是问题所在,当我简单地说ItemsSource="{Binding}"它终于奏效了。

以下是可能遇到相同问题并希望从中受益的人的代码:

数据背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace WpfDataGridWithDataTable
{
    public class Article
    {
        public Article()
        {

        }
        private int _modelNumber;
        public int ModelNumber
        {
            get { return _modelNumber; }
            set { _modelNumber = value; OnPropertyChanged("ModelNumber"); }
        }

        private string _modelName;
        public string ModelName
        {
            get { return _modelName; }
            set { _modelName = value; OnPropertyChanged("ModelName"); }
        }

        private decimal _unitCost;
        public decimal UnitCost
        {
            get { return _unitCost; }
            set { _unitCost = value; OnPropertyChanged("UnitCost"); }
        }

        private string _description;
        public string Description
        {
            get { return _description; }
            set { _description = value; OnPropertyChanged("Description"); }
        }


        #region INotifyPropertyChanged Membres

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }
        #endregion
    }
    public class ListArticles : ObservableCollection<Article>
    {
        public Article a;
        public ListArticles()
        {
            a = new Article();
            this.Add(a);

        }


    }

}

XAML代码:

<Window x:Class="WpfDataGridWithDataTable.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication18"
        Title="Window1" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="480" Width="760">

     <Window.Resources>
            <CollectionViewSource x:Key="cvsListArticles" Source="Article">

            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="ModelName"/>
            </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
        </Window.Resources> 


    <Grid
        Name="gridPanel">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <DataGrid Name="dataGrid1"  
            AutoGenerateColumns="True"  
            CanUserAddRows="True" 
            CanUserDeleteRows="True"
            CanUserResizeColumns="True"
            IsSynchronizedWithCurrentItem="True"
            ItemsSource="{Binding}" Grid.ColumnSpan="2" >

            <DataGrid.GroupStyle>

                <GroupStyle>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Margin" Value="0,0,0,5"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type GroupItem}">
                                        <Expander IsExpanded="True" Background="#FF112255" BorderBrush="#FF002255" Foreground="#FFEEEEEE" BorderThickness="1,1,1,5">
                                            <Expander.Header>
                                                <DockPanel>
                                                    <TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
                                                </DockPanel>
                                            </Expander.Header>
                                            <Expander.Content>
                                                <ItemsPresenter />
                                            </Expander.Content>
                                        </Expander>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </DataGrid.GroupStyle>
        </DataGrid>

        <Button 
                Grid.Row="1"
                Grid.Column="0"
                HorizontalAlignment="Left"
                Width="100"
                Name="btnAdd"
                Content="Add Item"
                Click="btnAdd_Click">
        </Button>
        <Button
                Grid.Row="1"
                Grid.Column="1"
                HorizontalAlignment="Right"
                Width="100"
                Name="btnDelete"
                Content="Delete Item"
                Click="btnDelete_Click" >
        </Button>
        <Button Content="Group" Grid.ColumnSpan="2" Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="294,5,0,0" Name="GroupButton" VerticalAlignment="Top" Width="145" Click="GroupButton_Click" />
    </Grid>
</Window>

表单背后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfDataGridWithDataTable
{

    public partial class Window1 : Window
    {
        private ListArticles myList;
        public Window1()
        {
            InitializeComponent();



            myList = new ListArticles();


            this.DataContext = myList;

        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            myList.Add(new Article());
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            myList.Remove(this.dataGrid1.SelectedItem as Article);
        }

        private void GroupButton_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView cvsListArticles = CollectionViewSource.GetDefaultView(dataGrid1.ItemsSource);
            if (cvsListArticles != null && cvsListArticles.CanGroup == true)
            {
                cvsListArticles.GroupDescriptions.Clear();
                cvsListArticles.GroupDescriptions.Add(new PropertyGroupDescription("ModelName"));
            }
        }


    }
}