WPF: creating a ListView with the ListItems extension

So, I want a list of elements that expand when they are selected to show more information (without toggleButton).

I believe there are several ways to do this, but I started by having a ListView associated with the viewModels collection and then defining the ViewModel as Expander. The problem here was in linking the selected option to the extension.

I started to get some ideas on how this could be done differently. Perhaps modding a ControlTemplate from a ListView so that its elements are set as my own extender type. But I'm not sure how well this works when a ListSource is installed.

The problem is that I'm not too sure that the best way is here.

+3
source share
1 answer

You can easily select the DataTemplateselected ListViewItemone by setting ListView.ItemContainerStyleand using the appropriate triggers.

Here is an example of how you can not only change the visual tree of a selected element, but also animate its properties at the same time.

<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>
+6
source

All Articles