Visual Studio / WPF > binding > RelativeSource={RelativeSource Self} > 複数のコントロールの色をNameで指定する


動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community

RelativeSource={RelativeSource Self}
という書き方にまだ慣れていない。

参考

実装

x:Nameに色を指定して、その文字列に基づいて色をつける実装をしてみた。
Implicit Key(x:Key未指定)でStyle指定。

MainWindow.xaml
<Window x:Class="_170615_t1700_relativeSource.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:_170615_t1700_relativeSource"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style TargetType="Rectangle">
            <Setter Property="Fill"
                    Value="{Binding Name, RelativeSource={RelativeSource Self}}"/>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel>
            <Rectangle x:Name="Yellow" Height="50"/>
            <Rectangle x:Name="Red" Height="50"/>
            <Rectangle x:Name="Blue" Height="50"/>
        </StackPanel>
    </Grid>
</Window>

将来、どういう場面でRelativeSource={RelativeSource Self}を必要とするかは今のところ不明。