背景:GridView、ListBox中的数据,如果需要不同的数据显示不同的模板,这个时候适合使用ItemTemplateSelector
1、window.Resources中定义两个数据模板,同一个数据集合,不同的数据使用不同的数据模板
<DataTemplate x:Key="yourDataTemp"><DataTemplate.Resources><Style TargetType="TextBlock"><Setter Property="FontSize" Value="20" /></Style></DataTemplate.Resources><Borderx:Name="border"Margin="5"Padding="5"BorderBrush="Red"BorderThickness="1"><DockPanel HorizontalAlignment="Center"><TextBlock Text="{Binding Path=name}" /><TextBlock>!</TextBlock></DockPanel></Border>
</DataTemplate><DataTemplate x:Key="myDataTemp"><WrapPanel Name="wrapPanel1" Orientation="Vertical"><WrapPanel.Style><Style TargetType="WrapPanel"><Setter Property="Background" Value="Transparent" /><Style.Triggers><DataTrigger Binding="{Binding Path=id}" Value="1"><Setter Property="Background" Value="Red" /></DataTrigger></Style.Triggers></Style></WrapPanel.Style><TextBlock Text="{Binding Path=id}" /><TextBlock Text="{Binding Path=name}" /></WrapPanel><!--<DataTemplate.Triggers>--><!-- 设置一下id为1的时候又干嘛 --><!--<DataTrigger Binding="{Binding Path=id}" Value="1"><Setter TargetName="wrapPanel1" Property="Background" Value="red"/></DataTrigger></DataTemplate.Triggers>-->
</DataTemplate>
-- 这里使用Student集合,属性有id和name
2、创建一个新的类重写SelectTemplate
// 接上DataTemplateSelector接口
public class dataTemplateSelector : DataTemplateSelector
{// 重写方法public override DataTemplate SelectTemplate(object item, DependencyObject container){if (item != null){Student student = item as Student;int taskitem = student.id;var window = Application.Current.MainWindow;if (taskitem == 1)return window.FindResource("yourDataTemp") as DataTemplate;elsereturn window.FindResource("myDataTemp") as DataTemplate;}MessageBox.Show("没有模板啊");return null;}
}
在window.Resources中引入该类
<local:dataTemplateSelector x:Key="myDataTemplateSelector" />
3、在ListView中原本的DataTemplate替换为ItemTemplateSelector
<ListBoxWidth="300"Margin="10"HorizontalContentAlignment="Stretch"ItemTemplateSelector="{StaticResource myDataTemplateSelector}"ItemsSource="{Binding Source={StaticResource myData}}" />