Binding オブジェクトの持つ、RelativeSource プロパティの利用方法の紹介です。
バインディングを利用して、バインドするソースとして、バインドターゲットの UI 要素から相対位置に存在する UI 要素のプロパティを指定する時には、RelativeSource プロパティを利用することができます。
例えば、TextBox の Tooltip プロパティにバインドするバインドソースとして、TextBox の親(Grid)の親である Window の Title プロパティを利用することを考えてみます。
デザインタイムでは、UI 要素は下記の構造になっています。TextBox から、2 つ上位にある Window のプロパティを参照します。
Window
- Grid
- TextBox
TextBox.Tooltip プロパティには、RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window} として、RelativeSoure を利用し、Mode に FindAncestor、AncestorType に Window をそれぞれ指定しています。これで、TextBox のツールチップには「MainWindow X」という値が表示されるようになります。
<Window x:Class="WpfApp3.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:WpfApp3"
mc:Ignorable="d"
Title="MainWindow X" Height="350" Width="525">
<Grid>
<TextBox x:Name="textBox1"
Height="30"
Width="250"
Text="abc"
ToolTip="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=Title}"/>
</Grid>
</Window>