您的位置:首页 > Web前端 > CSS

WPF中ListView自定义选中元素样式

2012-07-20 09:36 232 查看
  在WPF中的ListView非常强大,利用各种Template可以实现许多自定义的样式与功能,今天遇到一个自定义选中样式的问题,弄了半天才找到解决方法,分享给大家。

  前台XAML代码:

<ListView Grid.Row="1" Name="LV_Test" SelectionMode="Multiple" Background="{x:Null}">
<ListView.Template>
<ControlTemplate>
<Border CornerRadius="10" BorderBrush="RoyalBlue" BorderThickness="5">
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" >
<ItemsPresenter />
</ScrollViewer>
</Border>
</ControlTemplate>
</ListView.Template>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border Name="BD_Collector" CornerRadius="5" Background="DarkSeaGreen" Width="auto" Height="30" Margin="5">
<Label Content="{Binding}" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" FontSize="13" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="BD_Collector" Property="Background" Value="YellowGreen" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="BD_Collector" Property="Background" Value="DarkGreen" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>


  这里首先用到了Template模板,主要是负责最上层的显示,也就是说整个ListView的控件外观,通过此模板设置可以替换掉控件默认的外观。上面的代码定义了一个边框Boder和ScrollViewer的滚动条控件来囊括内部的数据,具体数据的内容,就由ItemsPresenter 来决定。接下来是ItemsPanel,用来设置数据展示的布局,可以为StackPanel,WrapPanel等各种方式都可以,数据内容则是对应了Template中的ItemsPresenter元素。ItemContainerStyle是实现自定义样式的最关键控件,可以自定义Style应用于为每个项生成的容器元素。我就是把数据直接通过Setter填到了这个模版里的,然后定义Trigger来响应样式改变的动作。

  好了,到了这里,我还介绍一下另一个很常用的模板,Itemtemplate,用其Datatemplate也能自定义实现数据显示的样式,可是这里需要区分的是,Itemtemplate是位于ListViewItem内部的,虽然可以实现显示样式,但是它无法获取ListViewItem本身的样式,可以认为ItemContainerStyle是更外一层的模板。

  我直接在ItemContainerStyle中定义了其Template,并设置了Controltemplate,在其中定义了数据,给需要变色的控件命名为"BD_Collector",然后通过触发器来响应选中动作。之所以把数据写在ItemContainerStyle中,而不是另外写在Itemtemplate中,是因为Setter的TargetName只能识别到当前控件内的控件,在Itemtemplate中的控件是无法用于ItemContainerStyle中的。

  对应的后台代码:

string id = TB_CollectorID.Text.Trim();
IList<int> values = new List<int>();
for (int i = 0; i < 100;++i )  values.Add(i);
LV_Test.ItemsSource = values;


  最终结果:



  如果想把这个样式应用于多个ListView,可以把ItemContainerStyle内的Style定义成资源,然后在ListView中通用ItemContainerStyle属性使用该资源即可。

  转载请注明原址:/article/5813023.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: