开发者

UserControl property trigger for child control

开发者 https://www.devze.com 2023-02-03 20:44 出处:网络
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.

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:T开发者_如何学编程ype 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?


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号