开发者

WPF: Creating a ListView with expanding ListItems

So I want a list of items that when you select them they expand to show more info (no toggleButton).

I figure there are multiple ways to do this but what I started at was that I had a ListView bound to the collection of viewModel开发者_运维百科s and then defined the ViewModel view as Expander. Problem here was binding the selected one to be expanded.

I started getting multiple ideas on how this could be done differently. Perhaps modding the ControlTemplate of the ListView to have it's items set as my own type of expander. But I'm not sure how well that works when the ItemsSource is set for the list.

Problem is I'm not too sure what the best way here is.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜