이 문서는 수동으로 번역한 것입니다. 원본 텍스트를 보려면 포인터를 문서의 문장 위로 올리십시오.
번역
원본
이 항목은 아직 평가되지 않았습니다.- 이 항목 평가

방법: DataGrid 컨트롤에서 데이터 그룹화, 정렬 및 필터링

Silverlight

경우에 따라 DataGrid에서 데이터를 그룹화, 정렬 및 필터링하여 다양한 방식으로 보는 것이 유용할 수 있습니다. DataGrid 에서 데이터를 그룹화, 정렬 및 필터링하려면 이러한 함수를 지원하는 컬렉션 뷰에 바인딩합니다. 그런 다음 내부 데이터에 영향을 주지 않고 컬렉션 뷰에서 데이터를 조작할 수 있습니다. 컬렉션 뷰의 변경 사항은 DataGrid UI(사용자 인터페이스)에 반영됩니다.

PagedCollectionView 클래스는 IEnumerable 인터페이스를 구현하는 데이터 소스에 그룹화, 정렬 및 페이징 기능을 제공합니다. 이 예제에서 Task 개체의 컬렉션은 PagedCollectionView에 래핑됩니다. PagedCollectionView DataGridItemsSource로 사용됩니다. 그룹화, 정렬 및 필터링은 PagedCollectionView에서 수행되며 DataGrid UI에 표시됩니다.

PagedCollectionView 는 또한 DataGrid와 함께 사용할 수 있는 페이징 기능을 제공합니다. 페이징의 예를 보려면 DataPager 컨트롤을 참조하십시오.

이 샘플을 실행합니다.

DataGrid 컨트롤에서 데이터를 그룹화, 정렬 및 필터링하려면 DataGrid를 이러한 함수를 지원하는 컬렉션 뷰에 바인딩합니다. 이 예제에서는 DataGridTask 개체의 List<T>에 대해 이러한 함수를 제공하는 PagedCollectionView에 바인딩됩니다.

DataGrid를 PagedCollectionView에 바인딩하려면

  1. IEnumerable 인터페이스를 구현하는 데이터 컬렉션을 만듭니다.

    참고 참고:

    컬렉션의 개체는 DataGrid가 속성 변경 및 편집 내용에 제대로 응답하도록 하기 위해 INotifyPropertyChanged 변경된 인터페이스 및 IEditableObject 인터페이스를 구현해야 합니다.

  2. PagedCollectionView 를 만들고 데이터 컬렉션을 생성자에게 전달합니다.

  3. DataGrid.ItemsSource 속성을 PagedCollectionView로 설정합니다.

    
    // Create a collection to store task data.
    ObservableCollection<Task> taskList = new ObservableCollection<Task>();
    // Generate some task data and add it to the task list.
    for (int i = 1; i <= 14; i++)
    {
        taskList.Add(new Task()
        {
            ProjectName = "Project " + ((i % 3) + 1).ToString(),
            TaskName = "Task " + i.ToString(),
            DueDate = DateTime.Now.AddDays(i),
            Complete = (i % 2 == 0),
            Notes = "Task " + i.ToString() + " is due on "
                  + DateTime.Now.AddDays(i) + ". Lorum ipsum..."
        });
    }
    
    PagedCollectionView taskListView = new PagedCollectionView(taskList);
    this.dataGrid1.ItemsSource = taskListView;
    
    
    

DataGrid 에서 항목이 그룹화되는 방법을 지정하려면 PropertyGroupDescription 형식을 사용하여 소스 뷰에서 항목을 그룹화합니다.

DataGrid에서 항목을 그룹화하려면

  1. PropertyGroupDescription 을 만들고 그룹화할 기준이 되는 속성의 이름을 생성자에게 전달합니다.

  2. PropertyGroupDescription PagedCollectionView.GroupDescriptions 컬렉션에 추가합니다.

  3. PropertyGroupDescription 의 추가 인스턴스를 PagedCollectionView.GroupDescriptions 컬렉션에 추가하여 더 많은 그룹화 수준을 추가합니다.

    
    if (taskListView.CanGroup == true)
    {
        // Group tasks by ProjectName...
        taskListView.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
        // Then group by Complete status.
        taskListView.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
    }
    
    
    

DataGrid 에서 항목이 그룹화되면 각 그룹에 머리글이 포함됩니다. 사용자 지정 Style을 정의하고 이를 RowGroupHeaderStyles 컬렉션에 추가하여 DataGridRowGroupHeader의 모양을 변경할 수 있습니다. 여러 그룹화 수준이 있는 경우 각 그룹 수준에 서로 다른 스타일을 적용할 수 있습니다. 스타일은 정의된 순서대로 적용됩니다. 예를 들어 두 가지 스타일을 정의한 경우 첫 번째 스타일이 최상위 행 그룹에 적용됩니다. 두 번째 스타일은 두 번째 수준 및 그 하위 수준의 모든 행 그룹에 적용됩니다. DataGridRowGroupHeader DataContext는 머리글이 나타내는 CollectionViewGroup입니다.

행 그룹 머리글의 모양을 변경하려면

  1. DataGridRowGroupHeader TargetType을 사용하여 Style을 만듭니다.

  2. Style <DataGrid.RowGroupHeaderStyles> 태그 안에 넣습니다.

    
    <sdk:DataGrid.RowGroupHeaderStyles>
        <!-- Style for groups at top level -->
        <Style TargetType="sdk:DataGridRowGroupHeader">
            <Setter Property="PropertyNameVisibility" Value="Collapsed" />
            <Setter Property="Background" Value="#FF112255" />
            <Setter Property="Foreground" Value="#FFEEEEEE" />
            <Setter Property="SublevelIndent" Value="15" />
        </Style>
        <!-- Style for groups under the top level -->
        <Style TargetType="sdk:DataGridRowGroupHeader">
            <Setter Property="Background" Value="#44225566" />
        </Style>
    </sdk:DataGrid.RowGroupHeaderStyles>
    
    
    

DataGrid 에서 항목이 그룹화되면 다음 메서드를 사용하여 그룹을 수동으로 축소 및 확장할 수 있습니다.

  • 행 그룹 머리글에서 축소 또는 확장 화살표를 클릭합니다.

  • 행 그룹 머리글을 두 번 클릭합니다.

  • 행 그룹 머리글에 포커스가 있을 때 왼쪽 화살표 키를 누르면 그룹이 축소되고 오른쪽 화살표 키를 누르면 그룹이 확장됩니다.

프로그래밍 방식으로 그룹을 축소하거나 확장하려면 CollectionViewGroupCollapseRowGroup 또는 ExpandRowGroup 메서드로 전달합니다.

행 그룹을 축소하거나 확장하려면

  1. 축소하거나 확장하려는 그룹을 나타내는 CollectionViewGroup을 가져옵니다.

    참고 참고:

    Groups 컬렉션에서 CollectionViewGroup을 가져올 수 있습니다. 또는 GetGroupFromItem 메서드를 사용하여 다음과 같이 개별 CollectionViewGroup을 가져올 수도 있습니다.

    Dim cvg = dataGrid1.GetGroupFromItem(dataGrid1.SelectedItem, 0)
    

    CollectionViewGroup cvg = dataGrid1.GetGroupFromItem(dataGrid1.SelectedItem, 0);
    
  2. 그룹을 축소하려면 CollectionViewGroupCollapseRowGroup 메서드에 전달합니다. 하위 그룹도 모두 축소하려면 두 번째 인수를 true로 설정합니다.

  3. 그룹을 확장하려면 CollectionViewGroupExpandRowGroup 메서드에 전달합니다. 하위 그룹도 모두 확장하려면 두 번째 인수를 true로 설정합니다.

    다음 예제에서는 PagedCollectionView.Groups 컬렉션의 모든 그룹을 축소 또는 확장하는 방법을 보여 줍니다.

    
    Private Sub CollapseButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        Try
            For Each group As CollectionViewGroup In pcv.Groups
                dataGrid1.ScrollIntoView(group, Nothing)
                dataGrid1.CollapseRowGroup(group, True)
            Next
        Catch ex As Exception
            ' Could not collapse group.
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    
    
    
    
    private void CollapseButton_Click(object sender, RoutedEventArgs e)
    {
        PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
        try
        {
            foreach (CollectionViewGroup group in pcv.Groups)
            {
                dataGrid1.ScrollIntoView(group, null);
                dataGrid1.CollapseRowGroup(group, true);
            }
        }
        catch (Exception ex)
        {
            // Could not collapse group.
            MessageBox.Show(ex.Message);
        }
    }
    
    
    
    
    Private Sub ExpandButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        Try
            For Each group As CollectionViewGroup In pcv.Groups
                dataGrid1.ExpandRowGroup(group, True)
            Next
        Catch ex As Exception
            ' Could not expand group.
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    
    
    
    
    private void ExpandButton_Click(object sender, RoutedEventArgs e)
    {
        PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
        try
        {
            foreach (CollectionViewGroup group in pcv.Groups)
            {
                dataGrid1.ExpandRowGroup(group, true);
            }
        }
        catch (Exception ex)
        {
            // Could not expand group.
            MessageBox.Show(ex.Message);
        }
    }
    
    
    

DataGrid 에서 항목이 정렬되는 방법을 지정하려면 SortDescription 형식을 사용하여 소스 뷰에서 항목을 정렬합니다.

DataGrid에서 항목을 정렬하려면

  1. SortDescription 을 만들고 정렬 기준이 되는 속성의 이름을 생성자에게 전달합니다.

  2. SortDescription PagedCollectionView.SortDescriptions 컬렉션에 추가합니다.

  3. SortDescription 의 추가 인스턴스를 PagedCollectionView.SortDescriptions 컬렉션에 추가하여 추가 속성을 기준으로 정렬합니다.

    
    if (taskListView.CanSort == true)
    {
        // By default, sort by ProjectName.
        taskListView.SortDescriptions.Add(new SortDescription("ProjectName", ListSortDirection.Ascending));
    }
    
    
    

DataGrid 에서 항목을 필터링하려면 필터링 논리를 제공하는 메서드를 만든 다음 PagedCollectionView.Filter 속성을 사용하여 필터를 적용합니다.

DataGrid에서 항목을 필터링하려면

  1. 필터링 논리를 제공하는 메서드를 만듭니다. 메서드는 콜백으로 사용되고 Object 형식의 매개 변수를 사용합니다.

  2. PagedCollectionView.Filter 속성을 설정하여 데이터에 필터를 적용합니다.

  3. PagedCollectionView.Filter 속성을 null로 설정하여 필터를 제거합니다.

    다음 예제에서는 CheckBoxChecked일 때 필터를 적용하고 CheckBoxUnchecked일 때 필터를 제거합니다.

    
    private void CheckBox_Checked(object sender, RoutedEventArgs e)
    {
        PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
        if (pcv != null && pcv.CanFilter == true)
        {
            // Apply the filter.
            pcv.Filter = new Predicate<object>(FilterCompletedTasks);
        }
    }
    
    private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
    {
        PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
        if (pcv != null)
        {
            // Remove the filter.
            pcv.Filter = null;
        }
    }
    
    public bool FilterCompletedTasks(object t)
    {
        Task task = t as Task;
        return (task.Complete == false);
    }
    
    
    

다음 예제에서는 PagedCollectionView에서 데이터를 그룹화, 정렬 및 필터링하는 방법 및 DataGrid에 그룹화된 데이터, 정렬된 데이터 및 필터링된 데이터를 표시하는 방법을 보여 줍니다. Task 개체의 컬렉션은 PagedCollectionView에 래핑됩니다. PagedCollectionView DataGridItemsSource로 사용됩니다. 그룹화, 정렬 및 필터링은 PagedCollectionView에서 수행되며 DataGrid UI에 표시됩니다.

이 샘플을 실행합니다.


<!-- NOTE: 
  By convention, the sdk prefix indicates a URI-based XAML namespace declaration 
  for Silverlight SDK client libraries. This namespace declaration is valid for 
  Silverlight 4 only. In Silverlight 3, you must use individual XAML namespace 
  declarations for each CLR assembly and namespace combination outside the scope 
  of the default Silverlight XAML namespace. For more information, see the help 
  topic "Prefixes and Mappings for Silverlight Libraries". 
-->
<UserControl x:Class="DataGridGrouping.MainPage"
    xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="600" Height="500">
    <Grid x:Name="LayoutRoot" Background="White" Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>
        <sdk:DataGrid x:Name="dataGrid1">
            <sdk:DataGrid.RowGroupHeaderStyles>
                <!-- Style for groups at top level -->
                <Style TargetType="sdk:DataGridRowGroupHeader">
                    <Setter Property="PropertyNameVisibility" Value="Collapsed" />
                    <Setter Property="Background" Value="#FF112255" />
                    <Setter Property="Foreground" Value="#FFEEEEEE" />
                    <Setter Property="SublevelIndent" Value="15" />
                </Style>
                <!-- Style for groups under the top level -->
                <Style TargetType="sdk:DataGridRowGroupHeader">
                    <Setter Property="Background" Value="#44225566" />
                </Style>
            </sdk:DataGrid.RowGroupHeaderStyles>
        </sdk:DataGrid>
        <StackPanel Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Center">
            <TextBlock Text="Filter Completed Tasks " />
            <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
            <Button Content="Expand All Groups" Margin="10,0,0,0" Click="ExpandButton_Click" />
            <Button Content="Collapse All Groups" Margin="5,0,0,0" Click="CollapseButton_Click" />
        </StackPanel>
    </Grid>
</UserControl>



Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Windows.Data


Partial Public Class MainPage
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
        ' Create a collection to store task data.
        Dim taskList As ObservableCollection(Of Task) = New ObservableCollection(Of Task)

        ' Generate some task data and add it to the task list.
        For index = 1 To 14
            taskList.Add(New Task() With _
                         {.ProjectName = "Project " & ((index Mod 3) + 1).ToString(), _
                           .TaskName = "Task " & index.ToString(), _
                           .DueDate = Date.Now.AddDays(index), _
                           .Complete = (index Mod 2 = 0), _
                           .Notes = "Task " & index.ToString() & " is due on " & Date.Now.AddDays(index) & ". Lorum ipsum..." _
                         })
        Next

        Dim taskListView As New PagedCollectionView(taskList)
        Me.dataGrid1.ItemsSource = taskListView
        If taskListView.CanGroup = True Then
            ' Group tasks by ProjectName...
            taskListView.GroupDescriptions.Add(New PropertyGroupDescription("ProjectName"))
            ' Then group by Complete status.
            taskListView.GroupDescriptions.Add(New PropertyGroupDescription("Complete"))
        End If
        If taskListView.CanSort = True Then
            '// By default, sort by ProjectName.
            taskListView.SortDescriptions.Add(New SortDescription("ProjectName", ListSortDirection.Ascending))
        End If
    End Sub
    Private Sub CheckBox_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        If pcv IsNot Nothing & pcv.CanFilter = True Then
            ' Apply the filter.
            pcv.Filter = New Predicate(Of Object)(AddressOf FilterCompletedTasks)
        End If
    End Sub

    Private Sub CheckBox_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        If pcv IsNot Nothing Then
            ' Remove the filter.
            pcv.Filter = Nothing
        End If
    End Sub

    Public Function FilterCompletedTasks(ByVal t As Object) As Boolean
        Dim _task As New Task
        _task = t
        Return _task.Complete = False
    End Function
    Private Sub ExpandButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        Try
            For Each group As CollectionViewGroup In pcv.Groups
                dataGrid1.ExpandRowGroup(group, True)
            Next
        Catch ex As Exception
            ' Could not expand group.
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Private Sub CollapseButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim pcv As PagedCollectionView = Me.dataGrid1.ItemsSource
        Try
            For Each group As CollectionViewGroup In pcv.Groups
                dataGrid1.ScrollIntoView(group, Nothing)
                dataGrid1.CollapseRowGroup(group, True)
            Next
        Catch ex As Exception
            ' Could not collapse group.
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class

Public Class Task
    Implements System.ComponentModel.INotifyPropertyChanged, IEditableObject
    ' The Task class implements INotifyPropertyChanged and IEditableObject 
    ' so that the datagrid can properly respond to changes to the 
    ' data collection and edits made in the DataGrid.

    ' Private task data.
    Private m_ProjectName As String = String.Empty
    Private m_TaskName As String = String.Empty
    Private m_DueDate As DateTime = Date.Now
    Private m_Complete As Boolean = False
    Private m_Notes As String = String.Empty

    ' Data for undoing canceled edits.
    Private temp_Task As Task = Nothing
    Private m_Editing As Boolean = False

    ' Public properties.
    Public Property ProjectName() As String
        Get
            Return Me.m_ProjectName
        End Get
        Set(ByVal value As String)
            If Not value = Me.m_ProjectName Then
                Me.m_ProjectName = value
                NotifyPropertyChanged("ProjectName")
            End If
        End Set
    End Property

    Public Property TaskName() As String
        Get
            Return Me.m_TaskName
        End Get
        Set(ByVal value As String)
            If Not value = Me.m_TaskName Then
                Me.m_TaskName = value
                NotifyPropertyChanged("TaskName")
            End If
        End Set
    End Property

    Public Property DueDate() As Date
        Get
            Return Me.m_DueDate
        End Get
        Set(ByVal value As Date)
            If Not value = Me.m_DueDate Then
                Me.m_DueDate = value
                NotifyPropertyChanged("DueDate")
            End If
        End Set
    End Property

    Public Property Complete() As Boolean
        Get
            Return Me.m_Complete
        End Get
        Set(ByVal value As Boolean)
            If Not value = Me.m_Complete Then
                Me.m_Complete = value
                NotifyPropertyChanged("Complete")
            End If
        End Set
    End Property

    Public Property Notes() As String
        Get
            Return Me.m_Notes
        End Get
        Set(ByVal value As String)
            If Not value = Me.m_Notes Then
                Me.m_Notes = value
                NotifyPropertyChanged("Notes")
            End If
        End Set
    End Property

    ' Implement INotifyPropertyChanged interface. 
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Sub NotifyPropertyChanged(ByVal propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    ' Implement IEditableObject interface.
    Public Sub BeginEdit() Implements IEditableObject.BeginEdit
        If Not Me.m_Editing Then
            Me.temp_Task = Me.MemberwiseClone()
            Me.m_Editing = True
        End If
    End Sub

    Public Sub CancelEdit() Implements IEditableObject.CancelEdit
        If m_Editing = True Then
            Me.ProjectName = Me.temp_Task.ProjectName
            Me.TaskName = Me.temp_Task.TaskName
            Me.DueDate = Me.temp_Task.DueDate
            Me.Complete = Me.temp_Task.Complete
            Me.Notes = Me.temp_Task.Notes
            Me.m_Editing = False
        End If
    End Sub

    Public Sub EndEdit() Implements IEditableObject.EndEdit
        If m_Editing = True Then
            Me.temp_Task = Nothing
            Me.m_Editing = False
        End If
    End Sub
End Class



using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace DataGridGrouping
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            // Create a collection to store task data.
            ObservableCollection<Task> taskList = new ObservableCollection<Task>();
            // Generate some task data and add it to the task list.
            for (int i = 1; i <= 14; i++)
            {
                taskList.Add(new Task()
                {
                    ProjectName = "Project " + ((i % 3) + 1).ToString(),
                    TaskName = "Task " + i.ToString(),
                    DueDate = DateTime.Now.AddDays(i),
                    Complete = (i % 2 == 0),
                    Notes = "Task " + i.ToString() + " is due on "
                          + DateTime.Now.AddDays(i) + ". Lorum ipsum..."
                });
            }

            PagedCollectionView taskListView = new PagedCollectionView(taskList);
            this.dataGrid1.ItemsSource = taskListView;
            if (taskListView.CanGroup == true)
            {
                // Group tasks by ProjectName...
                taskListView.GroupDescriptions.Add(new PropertyGroupDescription("ProjectName"));
                // Then group by Complete status.
                taskListView.GroupDescriptions.Add(new PropertyGroupDescription("Complete"));
            }
            if (taskListView.CanSort == true)
            {
                // By default, sort by ProjectName.
                taskListView.SortDescriptions.Add(new SortDescription("ProjectName", ListSortDirection.Ascending));
            }

        }
        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
            if (pcv != null && pcv.CanFilter == true)
            {
                // Apply the filter.
                pcv.Filter = new Predicate<object>(FilterCompletedTasks);
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = this.dataGrid1.ItemsSource as PagedCollectionView;
            if (pcv != null)
            {
                // Remove the filter.
                pcv.Filter = null;
            }
        }

        public bool FilterCompletedTasks(object t)
        {
            Task task = t as Task;
            return (task.Complete == false);
        }
        private void ExpandButton_Click(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    dataGrid1.ExpandRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not expand group.
                MessageBox.Show(ex.Message);
            }
        }
        private void CollapseButton_Click(object sender, RoutedEventArgs e)
        {
            PagedCollectionView pcv = dataGrid1.ItemsSource as PagedCollectionView;
            try
            {
                foreach (CollectionViewGroup group in pcv.Groups)
                {
                    dataGrid1.ScrollIntoView(group, null);
                    dataGrid1.CollapseRowGroup(group, true);
                }
            }
            catch (Exception ex)
            {
                // Could not collapse group.
                MessageBox.Show(ex.Message);
            }
        }

    }

    public class Task : System.ComponentModel.INotifyPropertyChanged, IEditableObject
    {
        // The Task class implements INotifyPropertyChanged and IEditableObject 
        // so that the datagrid can properly respond to changes to the 
        // data collection and edits made in the DataGrid.

        // Private task data.
        private string m_ProjectName = string.Empty;
        private string m_TaskName = string.Empty;
        private DateTime m_DueDate = DateTime.Now;
        private bool m_Complete = false;
        private string m_Notes = string.Empty;

        // Data for undoing canceled edits.
        private Task temp_Task = null;
        private bool m_Editing = false;

        // Public properties.
        [Display(Name = "Project")]
        public string ProjectName
        {
            get { return this.m_ProjectName; }
            set
            {
                if (value != this.m_ProjectName)
                {
                    this.m_ProjectName = value;
                    NotifyPropertyChanged("ProjectName");
                }
            }
        }

        [Display(Name = "Task")]
        public string TaskName
        {
            get { return this.m_TaskName; }
            set
            {
                if (value != this.m_TaskName)
                {
                    this.m_TaskName = value;
                    NotifyPropertyChanged("TaskName");
                }
            }
        }

        [Display(Name = "Due Date")]
        public DateTime DueDate
        {
            get { return this.m_DueDate; }
            set
            {
                if (value != this.m_DueDate)
                {
                    this.m_DueDate = value;
                    NotifyPropertyChanged("DueDate");
                }
            }
        }

        public bool Complete
        {
            get { return this.m_Complete; }
            set
            {
                if (value != this.m_Complete)
                {
                    this.m_Complete = value;
                    NotifyPropertyChanged("Complete");
                }
            }
        }

        public string Notes
        {
            get { return this.m_Notes; }
            set
            {
                if (value != this.m_Notes)
                {
                    this.m_Notes = value;
                    NotifyPropertyChanged("Notes");
                }
            }
        }

        // Implement INotifyPropertyChanged interface.
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        // Implement IEditableObject interface.
        public void BeginEdit()
        {
            if (m_Editing == false)
            {
                temp_Task = this.MemberwiseClone() as Task;
                m_Editing = true;
            }
        }

        public void CancelEdit()
        {
            if (m_Editing == true)
            {
                this.ProjectName = temp_Task.ProjectName;
                this.TaskName = temp_Task.TaskName;
                this.DueDate = temp_Task.DueDate;
                this.Complete = temp_Task.Complete;
                this.Notes = temp_Task.Notes;
                m_Editing = false;
            }
        }

        public void EndEdit()
        {
            if (m_Editing == true)
            {
                temp_Task = null;
                m_Editing = false;
            }
        }
    }
}


이 정보가 도움이 되었습니까?
(1500자 남음)

커뮤니티 추가 항목

추가
© 2013 Microsoft. All rights reserved.