[WPF][DataGrid] 全てのセル選択/解除をする

スポンサーリンク

本記事の概要

この記事では、DataGrid 上で全てのセル選択/解除をする方法について説明します。
※データ表示方法については過去記事「データグリッドにデータを表示する方法」を参照してください。

公式サイト情報はコチラを参照してください。

全てのセル選択/解除をする

DataGrid 上で全ての DataGrid 上の全てのセルを選択状態にするには SelectAllCells メソッドを、選択の解除をするには UnselectAllCells メソッドを使用します。

以下は2つのボタンを配置し、[全セル選択] ボタンをクリックすると、全てのセルを選択状態にし、[選択解除] ボタンをクリックすると全てのセルの選択を解除します。

XAMLの例

<Window x:Class="WpfSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfSample"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="25"/>
    <RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="0">
    <Button x:Name="btnSelectAllCells" Content="全セル選択" Click="btnSelectAllCells_Click" />
    <Button x:Name="btnUnselectAllCells" Content="選択解除" Click="btnUnselectAllCells_Click" />
</StackPanel>

<DataGrid x:Name="dataGrid" AutoGenerateColumns="False" Grid.Row="1">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding Id}" CanUserSort="False"/>
        <DataGridTextColumn Header="氏名" Binding="{Binding Name}" />
        <DataGridTextColumn Header="年齢" Binding="{Binding Age}"/>
        <DataGridTextColumn Header="郵便番号" Binding="{Binding ZipCode}"/>
        <DataGridTextColumn Header="住所" Binding="{Binding Address}" />
    </DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

C# の例

private void btnSelectAllCells_Click(object sender, RoutedEventArgs e)
{
    dataGrid.SelectAllCells();
}

private void btnUnselectAllCells_Click(object sender, RoutedEventArgs e)
{
    dataGrid.UnselectAllCells();
}
実行例

実行例

Please follow and like us:

コメント

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