WPF: Creating a ListView with expanding ListItems

久未见 提交于 2019-12-04 11:20:59

You can easily select the DataTemplate of the selected ListViewItem by setting ListView.ItemContainerStyle and using appropriate triggers.

Here's an example of how you can not only change the visual tree of the selected item, but also animate its properties at the same time as well.

<ListView ItemsSource="{Binding ...}">
  <ListView.Resources>
    <!-- this is what unselected items will look like -->
    <DataTemplate x:Key="DefaultItemTemplate">
      <TextBlock FontSize="12" Margin="0,0,10,0" Text="Unselected" />
    </DataTemplate>

    <DataTemplate x:Key="SelectedItemTemplate">
      <Border BorderBrush="Red" BorderThickness="2" Padding="5">
        <TextBlock FontSize="12" Margin="0,0,10,0" Text="Selected" />
      </Border>
    </DataTemplate>
  </ListView.Resources>

  <ListView.ItemContainerStyle>
    <Style TargetType="ListBoxItem">

      <!-- set properties for all items -->       
      <Setter Property="Margin" Value="0,2,0,2" />
      <Setter Property="Padding" Value="0,2,0,2" />
      <Setter Property="ContentTemplate" Value="{StaticResource DefaultItemTemplate}" />
      <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
          <!-- change what the selected item looks like -->
          <Setter Property="ContentTemplate" Value="{StaticResource SelectedItemTemplate}" />

          <!-- animate it as well -->
          <Trigger.EnterActions>
            <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation Storyboard.TargetProperty="MinHeight" To="80" Duration="0:0:1" />
              </Storyboard>
            </BeginStoryboard>
          </Trigger.EnterActions>
          <Trigger.ExitActions>
            <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation Storyboard.TargetProperty="MinHeight" To="0" Duration="0:0:1" />
              </Storyboard>
            </BeginStoryboard>
          </Trigger.ExitActions>

        </Trigger>
      </Style.Triggers>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!