WPF:使用扩展ListItem创建ListView

Ing*_*als 4 wpf templates listview expander mvvm

所以我想要一个项目列表,当你选择它们时,它们会展开以显示更多信息(没有toggleButton).

我想有多种方法可以做到这一点,但我开始的是我有一个ListView绑定到viewModel集合,然后将ViewModel视图定义为Expander.这里的问题是绑定所选的一个进行扩展.

我开始就如何以不同的方式完成这项工作获得多个想法.也许修改ListView的ControlTemplate,将它的项目设置为我自己的扩展器类型.但是我不确定在为列表设置ItemsSource时效果如何.

问题是我不太确定这里最好的方法是什么.

Jon*_*Jon 7

您可以通过设置和使用适当的触发器轻松选择DataTemplate所选ListViewItemListView.ItemContainerStyle.

下面是一个示例,说明如何不仅可以更改所选项目的可视树,还可以同时为其属性设置动画.

<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>
Run Code Online (Sandbox Code Playgroud)