WPF学习笔记(21)ListBox、ListView与控件模板

发布于:2025-07-03 ⋅ 阅读:(20) ⋅ 点赞:(0)


一、 ListBox默认控件模板详解

WPF 中的大多数控件都有默认的控件模板
这些模板定义了控件的默认外观和行为,包括控件的布局、背景、前景、边框、内容等。
官方文档:https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/controls/listbox-styles-and-templates
在这里插入图片描述
在工具箱拖入Button控件,鼠标右键→编辑模板→编辑副本在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
更改此模板来定制列表框的一些显示,比如一直显示水平垂直滚动条,可以直接更改Auto为 Visible:在这里插入图片描述
演示效果如下:
在这里插入图片描述

二、ItemsPresenter集合数据呈现

1. 概述

ltemsPresenter类在控件模板中显示集合数据的一个占位符,以便在运行时将其替换为所有集合数据。
而ContentPresenter则只能显示单一内容。
官方文档:https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.controls.itemspresenter?view=netframework-4.8
在这里插入图片描述

2. 示例

在这里插入图片描述
代码和运行结果如下

    <Grid>
        <ListBox x:Name="listBox" d:ItemsSource="{d:SampleData ItemCount=5}" Width="300" Height="200">
            <ListBox.Template>
                <ControlTemplate TargetType="ListBox">
                    <Border BorderBrush="Aqua" BorderThickness="2" CornerRadius="50">
                        <!--如果要多次呈现内容,需要使用布局-->
                        <StackPanel>
                            <ItemsPresenter/>
                            <Rectangle Width="auto" Height="10" Fill="Red"/>
                            <ItemsPresenter/>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </ListBox.Template>
        </ListBox>
    </Grid>
 public class Stu
 {
     public int Id { get; set; }
     public string Name { get; set; }
     public int Score { get; set; }
     public Stu(int id, string name, int score)
     {
         Id = id;
         Name = name;
         Score = score;
     }
 }
 public partial class MainWindow : Window
 {
     public MainWindow()
     {
         InitializeComponent();

         List<Stu> list = new List<Stu>
         {
             new Stu(1, "张三",100),
             new Stu(2, "李四", 80),
             new Stu(3, "王五", 75)
         };

         listBox.DisplayMemberPath = "Name";
         listBox.ItemsSource = list;
     }
 }

在这里插入图片描述

三、 ListView默认控件模板详解

1. 概述

官方文档:https://learn.microsoft.com/zh-cn/dotnet/desktop/wpf/controls/listview-styles-and-templates

在工具箱拖入ListView控件,删除<ListView.View></ListView.View>内的所有内容,鼠标右键→编辑模板→编辑副本
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2. 示例

在这里插入图片描述
参照官方文档中示例:

<!--创建标题和内容模板-->
  <Style x:Key="{x:Static GridView.GridViewScrollViewerStyleKey}" TargetType="ScrollViewer">
     <Setter Property="Template">
         <Setter.Value>
             <ControlTemplate TargetType="ScrollViewer">
                 <Grid Background="{TemplateBinding Background}" ShowGridLines="True">
                     <!--第二行,第二列为滚动条,可设置Visibility属性为True-->
                     <Grid.ColumnDefinitions>
                         <ColumnDefinition Width="*" />
                         <ColumnDefinition Width="Auto" />
                     </Grid.ColumnDefinitions>
                     <Grid.RowDefinitions>
                         <RowDefinition Height="*" />
                         <RowDefinition Height="Auto" />
                     </Grid.RowDefinitions>

                     <DockPanel Margin="{TemplateBinding Padding}">
                         <!--头部标题-->
                         <ScrollViewer DockPanel.Dock="Top"
                                       HorizontalScrollBarVisibility="Hidden"
                                       VerticalScrollBarVisibility="Hidden"
                                       Focusable="false">
                             <GridViewHeaderRowPresenter Margin="2,0,2,0"
                                       Columns="{Binding Path=TemplatedParent.View.Columns, RelativeSource={RelativeSource TemplatedParent}}"
                                       ColumnHeaderContainerStyle="{Binding Path=TemplatedParent.View.ColumnHeaderContainerStyle, RelativeSource={RelativeSource TemplatedParent}}"
                                       ColumnHeaderTemplate="{Binding Path=TemplatedParent.View.ColumnHeaderTemplate,RelativeSource={RelativeSource TemplatedParent}}"
                                       ColumnHeaderTemplateSelector="{Binding Path=TemplatedParent.View.ColumnHeaderTemplateSelector, RelativeSource={RelativeSource TemplatedParent}}"
                                       AllowsColumnReorder="{Binding Path=TemplatedParent.View.AllowsColumnReorder, RelativeSource={RelativeSource TemplatedParent}}"
                                       ColumnHeaderContextMenu="{Binding Path=TemplatedParent.View.ColumnHeaderContextMenu, RelativeSource={RelativeSource TemplatedParent}}"
                                       ColumnHeaderToolTip="{Binding Path=TemplatedParent.View.ColumnHeaderToolTip, RelativeSource={RelativeSource TemplatedParent}}"
                                       SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                         </ScrollViewer>
                         <!--滚动内容-->
                         <ScrollContentPresenter Name="PART_ScrollContentPresenter"
                             KeyboardNavigation.DirectionalNavigation="Local"
                             CanContentScroll="True"
                             CanHorizontallyScroll="False"
                             CanVerticallyScroll="False" />
                     </DockPanel>
                     <!--定义水平滚动条-->
                     <ScrollBar Name="PART_HorizontalScrollBar"
                                Orientation="Horizontal"
                                Grid.Row="1"
                                Maximum="{TemplateBinding ScrollableWidth}"
                                ViewportSize="{TemplateBinding ViewportWidth}"
                                Value="{TemplateBinding HorizontalOffset}"
                                Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" />
                     <!--定义垂直滚动条-->
                     <ScrollBar Name="PART_VerticalScrollBar"
                                Grid.Column="1"
                                Maximum="{TemplateBinding ScrollableHeight}"
                                ViewportSize="{TemplateBinding ViewportHeight}"
                                Value="{TemplateBinding VerticalOffset}"
                                Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" />

                 </Grid>
             </ControlTemplate>
         </Setter.Value>
     </Setter>
 </Style>

 <Color x:Key="ControlLightColor">White</Color>
 <Color x:Key="BorderMediumColor">#FF888888</Color>
 <Color x:Key="DisabledBorderLightColor">#FFAAAAAA</Color>

 <Style x:Key="{x:Type ListView}"
TargetType="ListView">
     <Setter Property="SnapsToDevicePixels" Value="true" />
     <Setter Property="OverridesDefaultStyle" Value="true" />
     <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
     <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
     <Setter Property="ScrollViewer.CanContentScroll" Value="true" />
     <Setter Property="VerticalContentAlignment" Value="Center" />
     <Setter Property="Template">
         <Setter.Value>
             <ControlTemplate TargetType="ListView">
                 <Border Name="Border" BorderThickness="1">
                     <Border.Background>
                         <SolidColorBrush Color="{StaticResource ControlLightColor}" />
                     </Border.Background>
                     <Border.BorderBrush>
                         <SolidColorBrush Color="{StaticResource BorderMediumColor}" />
                     </Border.BorderBrush>
                     <ScrollViewer Style="{DynamicResource
                 {x:Static GridView.GridViewScrollViewerStyleKey}}">
                         <ItemsPresenter />
                     </ScrollViewer>
                 </Border>
                 <ControlTemplate.Triggers>
                     <Trigger Property="IsGrouping" Value="true">
                         <Setter Property="ScrollViewer.CanContentScroll" Value="false" />
                     </Trigger>
                     <Trigger Property="IsEnabled" Value="false">
                         <Setter TargetName="Border" Property="Background">
                             <Setter.Value>
                                 <SolidColorBrush Color="{DynamicResource DisabledBorderLightColor}" />
                             </Setter.Value>
                         </Setter>
                     </Trigger>
                 </ControlTemplate.Triggers>
             </ControlTemplate>
         </Setter.Value>
     </Setter>
 </Style>

在这里插入图片描述

下面为简洁模式,不含标题行

<Style x:Key="myCT" TargetType="ListView">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListView">
                <Border Name="Border" BorderBrush="red" BorderThickness="1">
                <ScrollViewer>
                    <ItemsPresenter />
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>