wpfxamlbindingresourcedictionarystaticresource

XmlParseException when using binding in DataTemplate to access ressource with a non-string key


I have a DataTemplate in a style for ListViews.
ScriptAdvised is an enumeration.
The error comes from the StackPanel background attribute because if I remove it then it works.
My objective here is to access one of the brushes according to the Advised property (which is also of the ScriptAdvised type).

When I run my program, this exception is thrown :

System.Windows.Markup.XamlParseException : 'A 'Binding' cannot be set on the 'DeferrableContent' property of type 'ResourceDictionary'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.'

<DataTemplate>
    <DataTemplate.Resources>
        <SolidColorBrush x:Key="{x:Static logic:ScriptAdvised.Yes}" Color="Green" Opacity="0.15"/>
        <SolidColorBrush x:Key="{x:Static logic:ScriptAdvised.Limited}" Color="Yellow" Opacity="0.15"/>
        <SolidColorBrush x:Key="{x:Static logic:ScriptAdvised.No}" Color="Red" Opacity="0.15"/>
    </DataTemplate.Resources>
    <StackPanel Background="{StaticResource {Binding Advised}}" Orientation="Horizontal">
        <CheckBox/>
        <TextBlock Text="{Binding Name}"/>
    </StackPanel>
</DataTemplate>

I don't understand because I don't have any explicit ResourceDictionaries in my application.


Solution

  • Use a Style with DataTriggers to set the Background based on the value of Advised. Something like this:

    <DataTemplate>
        <DataTemplate.Resources>
            <SolidColorBrush x:Key="Yes" Color="Green" Opacity="0.15"/>
            <SolidColorBrush x:Key="Limited" Color="Yellow" Opacity="0.15"/>
            <SolidColorBrush x:Key="No" Color="Red" Opacity="0.15"/>
        </DataTemplate.Resources>
        <StackPanel Orientation="Horizontal">
            <StackPanel.Style>
                <Style TargetType="StackPanel">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Advised}" Value="{x:Static logic:ScriptAdvised.Yes}">
                            <Setter Property="Background" Value="{StaticResource Yes}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Advised}" Value="{x:Static logic:ScriptAdvised.Limited}">
                            <Setter Property="Background" Value="{StaticResource Limited}" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Advised}" Value="{x:Static logic:ScriptAdvised.No}">
                            <Setter Property="Background" Value="{StaticResource No}" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </StackPanel.Style>
            <CheckBox/>
            <TextBlock Text="{Binding Name}"/>
        </StackPanel>
    </DataTemplate>