12
9

More than 5 years have passed since last update.

【WPF】RelativeSource(バインディング)の使い方メモ

Last updated at Posted at 2019-03-05

RelativeSource

あるコントロールが、親のコントロールのプロパティを使いたいときに使う。
=ElementNameで名前を指定せずに、自分から相対的にバインド相手を指定する。

テンプレートとかで、親と同じ背景色やフォント色にしたい、というときによく使うっぽい。
(「AncestorLevel」を使って、自分からみて何番目にヒットしたAncestorTypeのものをつかう、という指定もできる)

a.xaml
<Canvas Margin="5" Grid.Column="0">
    <TextBlock Text="あいうえお"/>
    <!-- 上位のCanvasと同じ大きさにする -->
    <Border Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
            Height="{Binding ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
            Background="#330000FF" BorderBrush="Red" BorderThickness="1">
        <InkCanvas Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
            Height="{Binding ActualHeight, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
               Background="Transparent"/>
    </Border>
</Canvas>

ここで使っている「FindAncestor=祖先を探す」以外に、下記のようなものがある。

・Self
自分の別のプロパティを見る。
下の例では、幅と高さを同じにして、正方形にする、ということをしている。

a.xaml
<Border Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType=Canvas}}"
        Height="{Binding ActualWidth, RelativeSource={RelativeSource Self}" />

・TemplateParent
ControlTemplate、DataTemplateで、テンプレートを使う側のプロパティを取るために使う?
(試してない)

コード

参考

http://gushwell.ldblog.jp/archives/52328636.html
http://posaune.hatenablog.com/entry/20100114/1263426229

12
9
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
12
9