简体   繁体   中英

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM