实现这个功能的主要思路是替换LisView中的item模板和item选中时默认行为。
首先我们需要生成一个包含复选框和要显示文字的item模板。模板如下:
<
DataTemplate
x:Key
="ItemDataTemplate"
>
< CheckBox
x:Name ="checkbox"
Content ="{Binding}"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
</ DataTemplate >
< CheckBox
x:Name ="checkbox"
Content ="{Binding}"
IsChecked="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
</ DataTemplate >
模板定义中最重要的部分是对CheckBox的Binding,它将在视觉树中搜索ListViewItem并且同步ListViewItem中的IsSelected属性。
最后是为ListViewItem修改模板,以便于当你选中item时候不会把该行标记为已经选中,这个模板对于ListViewItem在默认情况下是没有触发器的。
<
ControlTemplate
x:Key
="ItemTemplate"
TargetType
="ListViewItem"
>
< Border
BorderThickness ="{TemplateBinding Border.BorderThickness}"
Padding ="{TemplateBinding Control.Padding}"
BorderBrush ="{TemplateBinding Border.BorderBrush}"
Background ="{TemplateBinding Panel.Background}"
SnapsToDevicePixels ="True" >
< ContentPresenter
Content ="{TemplateBinding ContentControl.Content}"
ContentTemplate ="{TemplateBinding ContentControl.ContentTemplate}"
HorizontalAlignment ="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment ="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels ="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</ Border >
</ ControlTemplate >
< Style TargetType ="ListViewItem" >
< Setter Property ="Template" Value ="{StaticResource ItemTemplate}" />
</ Style >
< Border
BorderThickness ="{TemplateBinding Border.BorderThickness}"
Padding ="{TemplateBinding Control.Padding}"
BorderBrush ="{TemplateBinding Border.BorderBrush}"
Background ="{TemplateBinding Panel.Background}"
SnapsToDevicePixels ="True" >
< ContentPresenter
Content ="{TemplateBinding ContentControl.Content}"
ContentTemplate ="{TemplateBinding ContentControl.ContentTemplate}"
HorizontalAlignment ="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment ="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels ="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</ Border >
</ ControlTemplate >
< Style TargetType ="ListViewItem" >
< Setter Property ="Template" Value ="{StaticResource ItemTemplate}" />
</ Style >
这个模板实现了与带有复选框的ListView控件相同的行为。
从这里下载例子的全部
代码。
转载于:https://blog.51cto.com/ddkangfu/108264