Search code examples
wpftriggersdatatriggerwpf-style

Hide whole Expander if header is empty


I have an Expander WPF control which header's template is a simple TextBlock. I want to hide whole expander if TextBlock.Text (which is filled dynamically from outside) is null or empty.

<Expander>
    <Expander.Header>
        <TextBlock Text="{Binding Path=Name}"/>
    </Expander.Header>
</Expander>

Solution

  • You can take reference from this example. Hide Expander ToggleButton if no child items in WPF

    Xaml

      <ListBox x:Name="lstbx">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Expander x:Name="exp">
                    <Expander.Header>
                        <TextBlock Text="{Binding Path=Name}"></TextBlock>
                    </Expander.Header>
                    <Expander.Style>
                        <Style TargetType="Expander">                          
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=Name}" Value="{x:Null}">
                                    <Setter  Property="Visibility" Value="Collapsed"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Expander.Style>
                </Expander>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    c#

         public Window1()
        {
            InitializeComponent();
            List<HeaderList> lst = new List<HeaderList>();
            lst.Add(new HeaderList(){Name= "Header1"});
            lst.Add(new HeaderList() { Name = "Header2" });
            lst.Add(new HeaderList() { });
            lst.Add(new HeaderList() { Name = "Header4" });
            lst.Add(new HeaderList() { });
            lst.Add(new HeaderList() { });
            lst.Add(new HeaderList() { Name = "Header7" });
            this.DataContext = this;
            lstbx.ItemsSource = lst;     
        }
    }
    public class HeaderList
    {
        public string Name { get; set; }
    }
    

    Result

    enter image description here