SHOEISHA iD

※旧SEメンバーシップ会員の方は、同じ登録情報(メールアドレス&パスワード)でログインいただけます

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

ComponentZine(ComponentOne)

SQL Serverのデータをグリッド表示するWPFアプリケーションの作成【増補改訂版】

ComponentOne Studioを活用したWindowsフォームアプリケーションの作成

  • このエントリーをはてなブックマークに追加

C1DataGridコントロールのデザイン時の設定

 C1DataGridコントロールは、XAMLを使うことで多くの部位のデザインを自由にカスタマイズすることができます。

C1DataGridコントロールのセルの操作

 C1DataGridコントロールでは、アプリケーションデザイン時により細かなセルの設定をすることができます。

セルの色の変更

 デザイン時にセルの色を変更することができます。これはXAMLのコードを追加します。

 まず、DataGridCellPresenterオブジェクトのスタイルを作成してBackground/Foregroundプロパティに変更したい色を設定します。

<Window.Resources>
    <Style x:Key="ColumnStyle" TargetType="c1:DataGridCellPresenter">
        <Setter Property="Background" Value="DarkGray" />
        <Setter Property="Foreground" Value="White" />
    </Style>
</Window.Resources>

 次に色を変更したい列のCellStyleプロパティを作成し、そのスタイルに作成したスタイルを設定します。

<c1:C1DataGrid Name="c1DataGrid1" AutoGenerateColumns="False">
    <c1:C1DataGrid.Columns>
        <c1:DataGridTextColumn Header="Column1" Binding="{Binding Column1, Mode=OneWay}" CellStyle="{StaticResource ColumnStyle}" />
    </c1:C1DataGrid.Columns>
</c1:C1DataGrid>

(参考:[DataGrid for WPF]セルの色を変更する方法は?

セルの編集禁止

 デザイン時にあらかじめセルの編集を禁止することができます。この操作は、列を明示的に定義して列のIsReadOnlyプロパティをTrueに設定します。

 処理はXAMLにコードを追加します。

<c1:C1DataGrid Name="c1DataGrid1" AutoGenerateColumns="False">
    <c1:C1DataGrid.Columns>
        <!--1列目のみ編集を禁止する-->
        <c1:DataGridTextColumn Header="Column1" Binding="{Binding Column1}" IsReadOnly="True" />
    </c1:C1DataGrid.Columns>
</c1:C1DataGrid>

(参考:[DataGrid for WPF]セルの編集を禁止する方法は?

セルの枠線の色の操作

 セルの枠線の色を変更することができます。

 まず、DataGridCellPresenterオブジェクトのスタイルをリソースで作成し、BorderThickness/BorderBrushプロパティを設定します。

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="504" Width="955" xmlns:my="http://schemas.componentone.com/winfx/2006/xaml">

    <Window.Resources>
        <Style x:Key="cellStyle" TargetType="my:DataGridCellPresenter">
            <Setter Property="BorderBrush" Value="Red" /> 
            <Setter Property="BorderThickness" Value="2" />         
        </Style>
    </Window.Resources>

 次に、C1DataGrid.CellStyleプロパティに、作成したスタイルを設定します。

    <Grid>   
        <my:C1DataGrid CellStyle="{StaticResource cellStyle}" />
    </Grid>    

(参考:[DataGrid for WPF]セルの枠線の色を変更する方法は?

セル内へのボタン表示が可能

 C1DataGridコントロールでは、セル内にボタンを表示することができます。それには、DataGridTemplateColumn列を作成して、CellTemplateプロパティにボタンを設定するだけです。これは、以下のようなXAMLを記述します。

<c1:C1DataGrid Name="c1DataGrid1">
    <c1:C1DataGrid.Columns>
        <c1:DataGridTemplateColumn>
            <c1:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="ボタン" Click="Button_Click" />
                </DataTemplate>
            </c1:DataGridTemplateColumn.CellTemplate>
        </c1:DataGridTemplateColumn>
    </c1:C1DataGrid.Columns>
</c1:C1DataGrid>

 また、このボタンをクリックした時の処理を作成することも可能です。

 例えば、ボタンをクリックした時に行数を取得するには、ボタンのClickイベントハンドラでsenderの親(DataGridCellPresenter型)からボタンのオブジェクトを取得し、そのRow.Indexプロパティを参照して行数を取得します。この処理は、ビハインドコードに記述します。

Visual Basic
Imports C1.WPF.DataGrid

Private Sub Button_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
    Dim button = TryCast(sender, Button)
    Dim presenter = TryCast(button.Parent, DataGridCellPresenter)
    MessageBox.Show(presenter.Row.Index & "行目のボタン")
End Sub
C#
using C1.WPF.DataGrid;

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    var presenter = button.Parent as DataGridCellPresenter;
    MessageBox.Show(presenter.Row.Index + "行目のボタン");
}

(参考:[DataGrid for WPF]セルにボタンを表示する方法は?

セル入力時のIMEモードが設定可能

 セルへのデータ入力時に、テキストホックスのIMEモードのオンオフや入力する文字種を設定することができます。

 セルでのIMEモードの自動起動は、C1DataGridコントロールの「BeganEdit」イベントハンドラで、編集用コントロールであるテキストボックスのIMEモードを設定します。この処理はビハインドコードで記述します。

 例えば、セル編集開始時にIMEモードをカタカナに設定して自動起動するには、まずBeganEditイベントハンドラを定義します。次に、このイベントハンドラ内でInputMethodクラスのSetPreferredImeConversionModeメソッドを実行します。メソッドの引数にImeConversionModeValues列挙体のメンバを指定することで、起動時のIMEモードを選ぶことができます。

Visual Basic
Public Sub New()
    nitializeComponent()
    AddHandler c1DataGrid1.BeganEdit, AddressOf c1DataGrid1_BeganEdit
End Sub

Private Sub c1DataGrid1_BeganEdit(sender As Object, e As C1.WPF.DataGrid.DataGridBeganEditEventArgs)
    If TypeOf e.EditingElement Is System.Windows.Controls.TextBox Then
        Dim txt As System.Windows.Controls.TextBox = DirectCast(e.EditingElement, System.Windows.Controls.TextBox)
        InputMethod.SetPreferredImeConversionMode(txt, ImeConversionModeValues.Katakana)
        InputMethod.SetPreferredImeState(txt, InputMethodState.[On])
    End If
End Sub
C#
public MainWindow()
{
    InitializeComponent();
    c1DataGrid1.BeganEdit += c1DataGrid1_BeganEdit;
 }
 
void c1DataGrid1_BeganEdit(object sender, C1.WPF.DataGrid.DataGridBeganEditEventArgs e)
{
    if (e.EditingElement is System.Windows.Controls.TextBox) 
    { 
        var txt = ((System.Windows.Controls.TextBox)(e.EditingElement));
        InputMethod.SetPreferredImeConversionMode(txt, ImeConversionModeValues.Katakana);
        InputMethod.SetPreferredImeState(txt, InputMethodState.On);
    }
}
ImeConversionModeValues列挙体のメンバ
メンバー名 説明
Alphanumeric 英数字変換モードを使用します。
CharCode 文字コード変換モードを使用します。
DoNotCare どの入力変換方法を使用しても問題ありません。実際の変換方法は不確定です。
Eudc EUDC(外字)変換モードを使用します。
Fixed 固定変換モードを使用します。
FullShape 全角変換モードを使用します。
Katakana カタカナ変換モードを使用します。
Native ネイティブ文字(ひらがな、ハングル、漢字)変換モードを使用します。
NoConversion どの入力変換も実行しません。
Roman ローマ字変換モードを使用します。
Symbol 記号変換モードを使用します。

(参考:[DataGrid for WPF]編集中のセルにIMEモードを設定する方法
(参考:[DataGrid for WPF]セルの編集用コントロールを取得する方法/イベントをハンドリングする方法

マウスでクリックしたセルの値を取得する

 アプリケーションによっては、マウスでクリックしたセルの値を取得したい場合があります。その場合は、各マウスクリックイベントでクリックされたセルの座標を取得し、その座標をGetCellFromPointメソッドに引き渡すことで、クリックしたセルを参照することができます。

 次のコードは、セルをマウスで右クリックした時に、クリックされたセルの行列番号とその値をメッセージボックスで表示します。

 まず、MouseRightButtonDownイベントハンドラを定義します。次に、そのイベントハンドラ内で引数eのGetPositionメソッドを使用してセルの座標を取得します。そして、その座標をC1DataGridコントロールのGetCellFromPointメソッドに渡すと、そのセルをDataGridCellオブジェクトとして返してきます。あとは、DataGridCellオブジェクトのプロパティを参照すれば、セルの行列番号や値を取得することができます。

Visual Basic
Public Sub New()
    ' この呼び出しはデザイナーで必要です。
    InitializeComponent()

    ' InitializeComponent() 呼び出しの後で初期化を追加します。
    Me.C1DataGrid1.ItemsSource = newds.収穫量一覧

    'クリックしたセルの取得
    AddHandler C1DataGrid1.MouseRightButtonDown, AddressOf C1DataGrid1_MouseRightButtonDown

End Sub

'クリックしたセルの取得
Private Sub C1DataGrid1_MouseRightButtonDown(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs)
    Dim wnd As Window = Window.GetWindow(Me)
    Dim point As Point = e.GetPosition(wnd)
    Dim cell As C1.WPF.DataGrid.DataGridCell = C1DataGrid1.GetCellFromPoint(point)

    If cell IsNot Nothing Then
        MessageBox.Show(String.Format("Cell Click [{0}, {1}]", cell.Row.Index, cell.Column.Index) & ":" & cell.Value)
    End If
End Sub
C#
public MainWindow()
{
    InitializeComponent();
    this.c1DataGrid1.ItemsSource = newds.収穫量一覧;

    // クリックしたセルの取得
    c1DataGrid1.MouseRightButtonDown += c1DataGrid1_MouseRightButtonDown;
}

// クリックしたセルの取得
void c1DataGrid1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    Window w = Window.GetWindow(this);
    Point point = e.GetPosition(w);
    C1.WPF.DataGrid.DataGridCell cell = c1DataGrid1.GetCellFromPoint(point);

    if (cell != null)
    {
        MessageBox.Show(String.Format("Cell Click [{0}, {1}]", cell.Row.Index, cell.Column.Index) + ":" + cell.Value);
    }
}

(参考:[DataGrid for WPF]マウスでクリックされたセルを取得する方法

ヘッダの設定

 グリッドのヘッダに対するデザイン操作や機能に対してもカスタマイズすることができます。

列ヘッダのテキストの配置

 列ヘッダの文字列の表示位置を設定するには、XAMLで列ヘッダのHeaderプロパティにTextBlockを配置して、TextBlockのHorizontalAlignment、VerticalAlignmentプロパティを設定します。

<c1:C1DataGrid Name="C1DataGrid1" AutoGeneratingColumn="C1DataGrid1_AutoGeneratingColumn">
    <c1:C1DataGrid.Columns>
        <c1:DataGridTextColumn>
            <c1:DataGridTextColumn.Header>
                <TextBlock Text="列ヘッダ" HorizontalAlignment="Center" VerticalAlignment="Center" />
            </c1:DataGridTextColumn.Header>
        </c1:DataGridTextColumn>
    </c1:C1DataGrid.Columns>
</c1:C1DataGrid>

(参考:[DataGrid for WPF]列ヘッダのテキストの配置を設定する方法は?

次のページ
GUIの作成

この記事は参考になりましたか?

  • このエントリーをはてなブックマークに追加
ComponentZine(ComponentOne)連載記事一覧

もっと読む

この記事の著者

瀬戸 遥(セト ハルカ)

8ビットコンピュータの時代からBASICを使い、C言語を独習で学びWindows 3.1のフリーソフトを作成、NiftyServeのフォーラムなどで配布。Excel VBAとVisual Basic関連の解説書を中心に現在まで40冊以上の書籍を出版。近著に、「ExcelユーザーのためのAccess再...

※プロフィールは、執筆時点、または直近の記事の寄稿時点での内容です

この記事は参考になりましたか?

この記事をシェア

  • このエントリーをはてなブックマークに追加
CodeZine(コードジン)
https://codezine.jp/article/detail/8490 2015/02/27 14:00

おすすめ

アクセスランキング

アクセスランキング

イベント

CodeZine編集部では、現場で活躍するデベロッパーをスターにするためのカンファレンス「Developers Summit」や、エンジニアの生きざまをブーストするためのイベント「Developers Boost」など、さまざまなカンファレンスを企画・運営しています。

新規会員登録無料のご案内

  • ・全ての過去記事が閲覧できます
  • ・会員限定メルマガを受信できます

メールバックナンバー

アクセスランキング

アクセスランキング