总所周知,wpf提供了数据模板,列表控件可以绑定数据实现批量显示同类型数据。不过同个数据模板显示不同的样式怎么办?这时我们可以用模板选择器。
首先我们可以将数据绑定到首先定义资源样式
<DataTemplate x:Key="Zero"> <ImageButton Style="{StaticResource RadiusButton}" BorderThickness="1" BorderBrush="{DynamicResource MainBlue}" Margin="50,0,50,0" FontFamily="黑体" VerticalAlignment="Top" CornerRadius="0" Width="120" Background="Transparent" Foreground="{DynamicResource MainBlue}" Height="40" Command="{Binding CloseCommand}" IsDefault="{Binding IsDefault}" FontSize="22" IsCancel="{Binding IsCancel}" CommandParameter="{Binding CommandParameter}" Text="{Binding Content}"/> </DataTemplate> <DataTemplate x:Key="One"> <ImageButton Style="{StaticResource RadiusButton}" Margin="50,0,50,0" FontFamily="黑体" VerticalAlignment="Top" CornerRadius="0" Width="120" BorderThickness="{Binding Index,Converter={StaticResource ButtonThicknessConverter}}" Background="{DynamicResource MainBlue}" BorderBrush="White" Foreground="White" Height="40" Command="{Binding CloseCommand}" IsDefault="{Binding IsDefault}" FontSize="22" IsCancel="{Binding IsCancel}" CommandParameter="{Binding CommandParameter}" Text="{Binding Content}"/> </DataTemplate>
新建模板选择器类,定义两个数据模板属性,对应资源样式的key,并继承DataTemplateSelector类,重写SelectTemplate方法
/// <summary> /// 模板选择器 /// wzw /// </summary> public class DataTypeTemplateSelector : DataTemplateSelector { public DataTemplate ZeroTemplate { get; set; } public DataTemplate OneTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { BlueButtonItem entity = item as BlueButtonItem; int index = entity.Index; if (index == 0) { return ZeroTemplate; } if (index == 1) { return OneTemplate; } return null; } }
然后绑定到datacontext后,在调用界面调用模板选择器。
<ItemsControl.ItemTemplateSelector> <local:DataTypeTemplateSelector ZeroTemplate="{StaticResource Zero}" OneTemplate="{StaticResource One}"></uc:DataTypeTemplateSelector> </ItemsControl.ItemTemplateSelector>