LoginSignup
5
3

More than 5 years have passed since last update.

【備忘録】DataGridのセルに対してStyle設定

Last updated at Posted at 2017-02-13

初めての投稿になります.
N番煎じ(というかそもそも投稿するようなことでも無い)と思いますが,備忘録として…

セルの内容をツールチップに表示

セルのマウスオーバー時にDataGridTextColumnの内容をツールチップに表示したい!ということで定義したStyle.

MainWindow.xaml
<Window.Resources>
    <Style x:Key="SelfToolTip" TargetType="TextBlock">
        <Setter Property="ToolTipService.ToolTip" 
                Value="{Binding Text, RelativeSource={RelativeSource Self}}" />
    </Style>
</Window.Resources>

ツールチップの表示内容(Value)はTextBlockのTextに設定.
これでツールチップに自身の内容を表示するようになります.

セルの内容で背景色と文字色を変更

セルの内容に応じてそのセルの背景色と文字色を変更したい!ということで定義したStyle.

MainWindow.xaml
<Window.Resources>
    <Style x:Key="DangerColorSet" TargetType="TextBlock">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Text}" 
                         Value="Danger">
                <Setter Property="Background" Value="Yellow"/>
                <Setter Property="Foreground" Value="Red"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

上記StyleではTextBlock(TargetType)のText(Path)が"Danger"の場合に背景色が黄色に,文字色が赤色に変化します.

あとは適用したいDataGridTextColumnのElementStyleに設定したKeyを指定してあげればOK.
ElementStyle="{StaticResource SelfToolTip}"とか
ElementStyle="{StaticResource DangerColorSet}"みたいな.

さいごに

初めまして傍猫といいます.そのまま「はたねこ」と読みます(どうでもいいね)
今後備忘録として少しずつでも投稿していこうと思います.
基本的にWPF(XAML,C#)に関する投稿が多くなると思いますが,機会があれば別の言語に関しても投稿していきたいと考えています.

ご指摘等していただけると嬉しいのでぜひよろしくお願いいたします.

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3