Silverlight編は次の回で紹介する予定です。あらかじめご了承ください。
対象読者
Visual BasicまたはVisual C#、および、Silverlight/WPFのプロジェクト作成方法、XAMLについて基礎的な知識がある方を対象としています。
必要な環境
下記を使ってプログラミングできる環境(筆者はこの環境で検証し執筆しています)。
- Visual Studio 2010
- Microsoft Silverlight 4 Tools for Visual Studio 2010
Microsoft Silverlight 4 Tools for Visual Studio 2010は、Microsoftダウンロードセンターより入手できます。Visual Studio 2010が準備できない方は、Visual Studio 2008およびVisual Studio 2008 Silverlight Tools 3.0の組み合わせでも構いません。ただし、この場合は本連載で取り上げるTipsが動作しない可能性もあります。あらかじめご了承ください。
今回紹介するTips
- 読み取り専用に設定する
- 項目をグループ化する
- グループ化のスタイルを設定する
- データを並び替えを禁止する
- 並べ替え可能な列を限定する
- ComboBoxで値を選択できるようにする
- 独自の列を追加する
- データの編集が開始/終了されたことを知る
01.読み取り専用に設定する
DataGridを読み取り専用にし、データを変更できないようにするにはIsReadOnlyプロパティにTrueを設定します。
下記は読み取り専用にする例です。
<DataGrid IsReadOnly="True"> :省略 </DataGrid>
'★★★読み取り専用にする★★★ CustomerDataGrid.IsReadOnly = True
// 読み取り専用にする customerDataGrid.IsReadOnly = true;
DataGridを読み取り専用にするにはIsReadOnlyプロパティにTrueを設定する。
02.項目をグループ化する
DataGridの任意の項目をグループ化するには ICollectionViewクラスを使用します。
XAMLでは<CollectionViewSource>タグに<CollectionViewSource.GroupDescriotion>タグを配置し、どの項目をグループ化するかを設定します。グループ化する項目は<PropertGroupDescription>で指定します。
また、コードからグループ化する場合はICollectionViewクラスのGroupDescription.Addメソッドでグループ化する項目を設定します。
下記は項目をグループ化する例です。
項目Titleをグループ化します。「Mr.」や「Ms.」でグループ化したデータが表示されます。
<Window.Resources>
<my:CustomerDS x:Key="CustomerDS" />
<CollectionViewSource x:Key="CustomerViewSource"
Source="{Binding Path=Customer, Source={StaticResource CustomerDS}}">
<CollectionViewSource.GroupDescriptions>
<!-- ★★★Title列をグループ化★★★ -->
<PropertyGroupDescription PropertyName="Title" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Window.Resources>
<Grid DataContext="{StaticResource CustomerViewSource}">
<DataGrid>
: 省略
</DataGrid>
</Grid>
Dim customerView As System.ComponentModel.ICollectionView =
CollectionViewSource.GetDefaultView(CustomerDataGrid.ItemsSource)
'ビューが存在しグループ化できるか?
If customerView IsNot Nothing And customerView.CanGroup = True Then
customerView.GroupDescriptions.Clear()
'★★★Title列をグループ化する★★★
customerView.GroupDescriptions.Add(New PropertyGroupDescription("Title"))
End If
System.ComponentModel.ICollectionView customerView =
CollectionViewSource.GetDefaultView(customerDataGrid.ItemsSource);
// ビューが存在しグループ化できるか?
if (customerView != null && customerView.CanGroup == true)
{
customerView.GroupDescriptions.Clear();
// ★★★Title列をグループ化する★★★
customerView.GroupDescriptions.Add(new PropertyGroupDescription("Title"));
}
項目のグループ化は XAMLでは<CollectionViewSource>,<CollectionViewSource.GroupDescription>で設定する。コードからはICollectionViewSourceクラスのGroupDescription.Addメソッドで設定する。

