xamluwpxaml-resources

XAML - Bind to value defined in resources from style defined in resources


I have a user control with defined resources. Here is some code for illustration.

<UserControl.Resources>
    <SolidColorBrush x:Key="foregroundColor" Color="Red"/>

    <Style x:Key="buttonFontIconStyle" TargetType="FontIcon">
        <Setter Property="FontFamily" Value="Segoe MDL2 Assets"></Setter>
        <Setter Property="Foreground" Value="{Binding ???}"></Setter>
    </Style>

    <Style x:Key="menuItemLabelStyle" TargetType="TextBlock">
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
        <Setter Property="Foreground" Value="{Binding ???}"></Setter>
    </Style>     
</UserControl.Resources>

Now, I wish to use value defined in foreground color for buttonFontIconStyle, menuItemLabelStyle (and many others). Is it somehow possible to bind to value from resources in resources, or is there a way to specifiy color once (in xaml preferrably) and use it in multiple resources styles?


Solution

  • You can use the StaticResource :

    <Style x:Key="buttonFontIconStyle" TargetType="FontIcon">
        <Setter Property="FontFamily" Value="Segoe MDL2 Assets"></Setter>
        <Setter Property="Foreground" Value="{StaticResource foregroundColor}"></Setter>
    </Style>
    
    <Style x:Key="menuItemLabelStyle" TargetType="TextBlock">
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
        <Setter Property="Foreground" Value="{StaticResource foregroundColor}"></Setter>
    </Style>