Splinti Splinti - 2 months ago 20
C# Question

Setter TargetName 'ContentPresenter' not recognized in Trigger

I have got a ContentPresenter and the Opacity of the Content should become 0.5 when the Button is disabled, but the Setter cant find it by TargetName. Is there something I am missing?

<Style TargetType="Button">
<Style.Triggers>
<Trigger Property="Tag" Value="MenuButton">
<Setter Property="Background" Value="{StaticResource BackgroundBrush}"/>
<Setter TargetName="ContentPresenter" Property="Opacity" Value="1.0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border BorderThickness="1,0,0,1" Background="{TemplateBinding Background}">
<ContentPresenter
x:Name="ContentPresenter"
Margin="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Opacity="1.0"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>
<Setter TargetName="ContentPresenter" Property="Opacity" Value="0.5"/>

</Trigger>
</Style.Triggers>
</Style>

ASh ASh
Answer

you can use ControlTemplate.Triggers to change ContentPresenter properties via Setters. "ContentPresenter" name is known only in template.

<Style TargetType="Button">
    <Style.Triggers>
        <Trigger Property="Tag" Value="MenuButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border BorderThickness="1,0,0,1" Background="{TemplateBinding Background}">
                            <ContentPresenter
                                x:Name="ContentPresenter"
                                Margin="1"
                                VerticalAlignment="Center"
                                HorizontalAlignment="Center"
                                Opacity="1.0"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/>
                                <Setter TargetName="ContentPresenter" Property="Opacity" Value="0.5"/>
                            </Trigger>

                            <Trigger Property="IsEnabled" Value="True">
                                <Setter Property="Background" Value="{StaticResource BackgroundBrush}"/>
                                <Setter TargetName="ContentPresenter" Property="Opacity" Value="1"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>

    </Style.Triggers>
</Style>