关于更改ListBox的ItemsPanel样式

   首先定义一个ListBoxItem的样式,用来显示相应的图片信息

<Style TargetType="{x:Type ListBoxItem}" >
  <Setter Property="Template">
    <Setter.Value>
    <ControlTemplate TargetType="{x:Type ListBoxItem}">
    <Border x:Name="border" Height="64" Width="64" Margin="5,1,5,1" BorderThickness="2" VerticalAlignment="Center" Background="Aqua">
      <Image Margin="5" Cursor="Hand" Stretch="Fill" HorizontalAlignment="Center" VerticalAlignment="Center" Source="{Binding Photo}" ToolTip="{Binding Name}"> </Image>
    </Border>
  <ControlTemplate.Triggers>
    <Trigger Property="IsFocused" Value="true" >
      <Setter Property="BorderBrush" Value="Beige" TargetName="border"/>
    </Trigger>
    <Trigger Property="IsMouseOver" Value="true">
      <Setter Property="BorderBrush" Value="BlanchedAlmond" TargetName="border"/>
    </Trigger>
    <Trigger Property="IsSelected" Value="true">
      <Setter Property="BorderBrush" Value="BurlyWood" TargetName="border"/>
    </Trigger>
  </ControlTemplate.Triggers>
  </ControlTemplate>
  </Setter.Value>
  </Setter>
</Style>

下面是更改ListBox的默认样式为,并且使用WrapPanel来展示图片,在使用的过程中需要注意一些方面。          

<ListBox x:Name="myListBox" Margin="0,8,0,12" Grid.Row="1" Background="Transparent" BorderBrush="Transparent"
  ItemsSource="{Binding MyPersonList}" ScrollViewer.CanContentScroll="False">
  <ListBox.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapPanel Orientation="Horizontal">
      </WrapPanel>
    </ItemsPanelTemplate>
  </ListBox.ItemsPanel>
</ListBox>

    通过修改ItemsPanelTemplate模板,我们能够使ListBox显示我们需要展示的东西,在这里需要注意一点的是上面是应用ListBoxItem的一种方式,还有下面一种方式,即在ListBox里添加一个x:Key="MyListBoxTemplate" 但是在下面进行引用的时候,必须使用

ItemContainerStyle="{StaticResource MyListBoxTemplate}" 进行引用,不能上面定义了Key而下面不使用ItemContainerStyle来进行引用,这样的话最终是不会为ListBoxItem添加样式的,所以必须成双成对的引用,这点我们需要注意,以上是自己使用的一点点心得体会。

你可能感兴趣的:(listbox)