Shameel Mohamed
Shameel Mohamed

Reputation: 637

wpf hide an element based on children count of another element in xaml

Using purely XAML, I want to hide an element, say a textblock or an image if a list or a stackpanel has elements.

For example, see the following code

<Label x:Name="LabelTobeHidden" 
       Content="No one has joined" 
       Visibility="Visible"
       />
<StackPanel x:Name="Players" Orientation="Vertical"/>

I can do this is cs, but I want to know of a way to do this solely in XAML to try my best to ensure that cs only has the application logic.

Edit:

I am adding elements to the stackpanel programmatically.

Upvotes: 0

Views: 789

Answers (1)

dymanoid
dymanoid

Reputation: 15197

You can use a DataTrigger in a Style for that.

This is our StackPanel to watch for:

<StackPanel x:Name="StackPanelToWatch" Orientation="Horizontal">
  <Rectangle Width="50" Height="50" Fill="Red"/>
</StackPanel>

And here is the Label to hide:

<Label Content="text">
  <Label.Style>
    <Style TargetType="Label">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Children.Count, ElementName=StackPanelToWatch}" Value="0">
          <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </Label.Style>
</Label>

Upvotes: 1

Related Questions