Jakub Loksa
Jakub Loksa

Reputation: 577

C# WPF - How to use child as a Style trigger

So I have multiple Grid elements in a StackPanel. The Grid elements have TextBlock elements as children.

What I want to do is to set a Style that changes the Visibility property to Collapsed if the TextBlock's Text property is "0".

So far I achieved the TextBlock collapsing, but not the whole Grid; the code is below:

    <StackPanel Grid.Column="1">

        <StackPanel.Resources>
            <Style>
                <Style.Triggers>
                    <Trigger Property="Text" Value="0">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </StackPanel.Resources>

        <Grid Margin="5,0,5,5" >
            <TextBlock Text="If this value is 0, I want the whole parent grid to Collapse." Padding="5"/>
        </Grid>

        <Grid Margin="5,0,5,5" >
            <TextBlock Text="Thank you StackOverflow!" Padding="5"/>
        </Grid>

    </StackPanel>

Upvotes: 0

Views: 1037

Answers (1)

Michal Ciechan
Michal Ciechan

Reputation: 13888

To do it via Styles you can use element name. E.g:

<StackPanel Grid.Column="1">
    <StackPanel.Style>
        <Style TargetType="StackPanel">
            <Style.Triggers>
                <!-- Here is how we bind to another control's property -->
                <DataTrigger Binding="{Binding Content, ElementName=SomexName}" Value="0">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>

    <Grid Margin="5,0,5,5" >
        <!-- You need to set this textbloc element name -->
        <TextBlock x:Name="SomexName" Text="If this value is 0, I want the whole parent grid to Collapse." Padding="5" />
    </Grid>

    <Grid Margin="5,0,5,5" >
        <TextBlock Text="Thank you StackOverflow!" Padding="5"/>
    </Grid>

</StackPanel>

Although I would recommmend using MVVM and exposing either a

  • IsVisible boolean property, which then you can use a boolean to visibility converter

See: Best Approach of setting the Visibility in MVVM

Upvotes: 1

Related Questions