为了方便读者学习,请 下载源代码。
首先,我们来看一下使用这个控件后的效果图:
我们再来看看实现这个控件的XAML代码:
    1 
<
common
:
DataGrid
 Name
="grdDataGrid"
 ItemsSource
="{
Binding
}"
 CheckBoxChecked
="grdDataGrid_CheckBoxChecked"
 ButtonClick
="grdDataGrid_ButtonClick"
 ComboBoxSelectionChanged
="grdDataGrid_ComboBoxSelectionChanged">
    2 
    
<
ListView.View
>
    3 
        
<
GridView
>
    4 
            
<
common
:
DataGridColumn
 Header
="First Name"
 ColumnType
="TextBlock"
 TextBlockTextPath
="LastName"
 ButtonValuePath
="ID" />
    5 
            
<
common
:
DataGridColumn
 Header
="Last Name"
 ColumnType
="ComboBox"
 ComboBoxTextPath
="LastName"
 ComboBoxDisplayMemberPath
="LastName"
 ComboBoxSelectedValuePath
="ID"
 HasDifferentDataContext
="True"
 SortPropertyName
="LastName" />
    6 
            
<
common
:
DataGridColumn
 Header
="ID"
 ColumnType
="CheckBox"
 CheckBoxValuePath
="ID"
 SortPropertyName
="ID"
 Width
="50" />
    7 
            
<
common
:
DataGridColumn
 Header
="Date of Birth"
 TextBlockTextPath
="DateOfBirth"
 TextBlockTextAlignment
="Right"
 SortPropertyName
="DateOfBirth"
 IsDefaultSortColumn
="True" />
    8 
        
</
GridView
>
    9 
    
</
ListView.View
>
   10 
</
common
:
DataGrid
>
我们可以看到,使用这个控件跟普通的ListView控件没有太多的区别。我们只需要在DataGridColumn中指定ColumnType为Button、CheckBox、ComboBox、TextBox等,默认为TextBlock,然后对应该类型设定相应的属性即可。而相关的排序、DataTemplate等功能则已经完全封装了。另外,普通的ListView控件的RoutedEventArgs中的信息太少,而取得SourceRowIndex、SourceColumnIndex、CurrentRowIndex、CurrentColumnIndex等则又很难实现,且非常重要,所以笔者也实现了自己的RoutedEventArgs,提供上述各种Index,方便大家在该控件的事件中直接使用。
下面的几篇文章我将对该控件中的各个重要方面进行一一讲解。