WPF Data trigger to apply style on parent element

1.5k views Asked by At

I have a Grid which contains a Scrollviewer. I would like to change the Grid's margin if the Vertical scrollbar is visible.

<Grid x:Name="TopGrid" Margin="50,10,100,10" Background="Gainsboro"  >
        <ScrollViewer x:Name="sv" VerticalScrollBarVisibility="Auto">
            <TextBlock x:Name="ItemText" Text="Description" />
         </ScrollViewer>
</Grid>

The DataTrigger condition in Scrollviewer should be this:

<DataTrigger Binding="{Binding ComputedVerticalScrollBarVisibility,
                                        ElementName=sv}" Value="Visible">
</DataTrigger>

and the grid's style should be changed to this:

<Setter TargetName="TopGrid" Property="Margin" Value="100"/>

How can I have the data trigger binding on Scrollviewer and change the style of the parent grid?

Thanks

1

There are 1 answers

4
dkozl On BEST ANSWER

If you want to change Grid.Margin based on some condition you could create Style for Grid with Trigger you posted but you need to move default Margin value into Setter otherwise DataTrigger won't be able to change that value

<Grid x:Name="TopGrid" Background="Gainsboro">
    <Grid.Style>
        <Style TargetType="{x:Type Grid}">
            <Setter Property="Margin" Value="50,10,100,10"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=sv, Path=ComputedVerticalScrollBarVisibility}" Value="Visible">
                    <Setter Property="Margin" Value="100"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Grid.Style>
    <ScrollViewer x:Name="sv" VerticalScrollBarVisibility="Auto">
        <TextBlock x:Name="ItemText" Text="Description" />
    </ScrollViewer>
</Grid>