[C#][WPF]DataGrid のカラムにタブキーでフォーカスしないようにしたい!

C#
記事内に広告が含まれています。

WPF で DataGrid を使って開発をしていると Tab キーによるフォーカス移動で DataGrid 内の特定の列だけフォーカスさせたい場面がある。

今回は、DataGrid の特定の列にタブストップしないようにする方法を紹介します。

カラムには IsTabStop がない

なぜ、今回の問題が生じるかといえば、DataGrid には IsTabStop プロパティがあるのですが、カラムには IsTabStop プロパティがありません。

IsTabStop プロパティは、”False” にしておくとタブキーでフォーカスが止まらないように出来ます。

対処方法

カラムではなく、個々のセルに対して設定することで対応することが出来ます。

以下、サンプルコードです。

    <!-- ResourcesにDataGridCellへ適用するスタイルを追加 -->
    <Window.Resources>
        <Style x:Key="UnTabStopCell" TargetType="{x:Type DataGridCell}">
            <Setter Property="IsTabStop" Value="False"/>    
        </Style>
    </Window.Resources>

    <Grid>
        <DataGrid
            IsTabStop="False"
            AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn
                    Header="Button"
                    Width="200">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="Button" Click="Button_Click" IsTabStop="True"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <!-- フォーカスさせたくないカラムのセルに定義したStyleを適用 -->
                <DataGridTextColumn
                    Binding="{Binding Key}"
                    Header="Key"
                    IsReadOnly="True"
                    Width="300" 
                    CellStyle="{StaticResource UnTabStopCell}"/>
                <DataGridTextColumn
                    Binding="{Binding Value}"
                    Header="Value"
                    IsReadOnly="True"
                    Width="300" 
                    CellStyle="{StaticResource UnTabStopCell}"/>
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

DataGridCell の Style で IsTabStop プロパティを設定することでタブキーでフォーカスが移動しないようになりました。

コメント

タイトルとURLをコピーしました