Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl property trigger for child control

Tags:

wpf

xaml

Depending on the IsEnabled property of my UserControl (true/false), I want the controls inside it have different colors. I want to do so with the 'magic' of XAML.

<UserControl.Resources>
    <Style x:Key="EnableDependent" TargetType="{x:Type Shape}">
        <Style.Triggers>
            <Trigger Property="{Binding Path=IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" Value="True">
                <Setter Property="Stroke" Value="White" />
            </Trigger>
            <Trigger Property="{Binding Path=IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" Value="False">
                <Setter Property="Stroke" Value="Black" />
            </Trigger>
        </Style.Triggers>
    </Style>
</UserControl.Resources>

The style is applied in a ViewBox where a Path is drawn:

    <Viewbox  Grid.Column="3" Width="18" Margin="5,5,2,5" MouseEnter="Dispatch_MouseEnter" DockPanel.Dock="Right" Stretch="Uniform">
        <Path Data="M0,1 L4,1 M2,0 L4,1 L2,2" Stretch="Fill" StrokeThickness="3" Width="12" Height="12" Style="{StaticResource EnableDependent}" />
    </Viewbox>

I get a runtime exception that a binding cannot be set in the 'Property' property of a trigger.

So what is the way to do this?

like image 980
Kay Zed Avatar asked Jan 09 '11 21:01

Kay Zed


1 Answers

Use a DataTrigger instead of a normal Trigger which is for internal property changes, it has a Binding-Property where you can do that.

<Style x:Key="EnableDependent" TargetType="{x:Type Shape}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" Value="True">
            <Setter Property="Stroke" Value="White" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" Value="False">
            <Setter Property="Stroke" Value="Black" />
        </DataTrigger>
    </Style.Triggers>
</Style>
like image 105
H.B. Avatar answered Oct 04 '22 21:10

H.B.