Search code examples
wpfbindingexpanderwpf-style

How to bind Expander's IsExpanded property to Items.Count of Expander's Content as ItemsControl in Style


As the title says, i want to bind the property IsExpanded of my Expander to the Items.Count property of the ItemsControl, which is the Content of the Expander. I need this binding for more expanders so a style or something like that would be nice. I already tried some stuff found here or on other sites, but nothing worked.

Here is my actual code:

<Style x:Key="ExpanderStyleKey" TargetType="Expander">

    <Style.Triggers>

        <DataTrigger Binding="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Content.Items.Count}" Value="0">

            <Setter Property="IsExpanded" Value="False"/>

        </DataTrigger>

    </Style.Triggers>

</Style>

Thank you for help!

EDIT:

Here is the code of one of my Expander:

<Expander Name="exp1" 
          Header="Expander1" 
          Style="{StaticResource ExpanderStyleKey}">

    <ItemsControl Name="itcMain"
                  ItemsSource="{Binding Path=ListInCodeBehind, Mode=OneWay}">

        <ItemsControl.Template>

            <ControlTemplate>

                <ScrollViewer VerticalScrollBarVisibility="Auto"
                          HorizontalScrollBarVisibility="Disabled">

                    <ItemsPresenter/>

                </ScrollViewer>

            </ControlTemplate>

        </ItemsControl.Template>

        <ItemsControl.ItemsPanel>

            <ItemsPanelTemplate>

                <WrapPanel/>

            </ItemsPanelTemplate>

        </ItemsControl.ItemsPanel>

        <ItemsControl.ItemTemplate>

            <DataTemplate>

                <TextBox Text="{Binding Path=ExampleProperty}"/>

            </DataTemplate>

        </ItemsControl.ItemTemplate>

    </ItemsControl>

</Expander>

Solution

  • Example,

    <Expander>
       <Expander.Style>
          <Style TargetType="Expander">
              <Setter Property="IsExpanded" Value="{Binding Content.Items.Count, Mode=OneWay, RelativeSource={RelativeSource Self}}"/>
          </Style>
       </Expander.Style>
       <Expander.Content>
          <ItemsControl>
              <ItemsControl.Items>
                  <TextBlock Text="Item1"/>
                  <TextBlock Text="Item2"/>
                  <TextBlock Text="Item3"/>
              </ItemsControl.Items>
          </ItemsControl>
       </Expander.Content>
     </Expander>