WPF: Creating a ListView with expanding ListItems

谁说我不能喝 提交于 2019-12-21 17:55:37

问题


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 viewModels 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.


回答1:


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>


来源:https://stackoverflow.com/questions/5303247/wpf-creating-a-listview-with-expanding-listitems

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