WPF 的 ItemsControl 数据绑定中,有时会遇到绑定的数据源是多种类型,并且需要对不同类型使用不同的模板。这个时候就需要用到 ItemTemplateSelector。
ItemTemplateSelector 是 DataTemplateSelector 类型,通常需要定义一个类继承 DataTemplateSelector。
项目结构:
创建一个模板选择类TestDataTemplateSelector:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace WpfApp2 { public class TestDataTemplateSelector: DataTemplateSelector { public DataTemplate HighTemplate { get; set; } public DataTemplate LowTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { var stu = (Student)item; if (stu.Result > 60) return HighTemplate; else return LowTemplate; } } }
MainWindow.xaml代码:
在Window.Resources中定义了两个模板HighTemplate和LowTemplate。
<Window x:Class="WpfApp2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp2" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <DataTemplate x:Key="HighTemplate"> <StackPanel> <TextBlock Text="{Binding Name}"/> <TextBlock Text="考的非常好!"/> </StackPanel> </DataTemplate> <DataTemplate x:Key="LowTemplate"> <StackPanel Background="Red"> <TextBlock Text="{Binding Name}"/> <TextBlock Text="电话家长警告!"/> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <ListBox x:Name="list" ItemsSource="{Binding Model}"> <ListBox.ItemTemplateSelector> <local:TestDataTemplateSelector HighTemplate="{StaticResource HighTemplate}" LowTemplate="{StaticResource LowTemplate}"/> </ListBox.ItemTemplateSelector> </ListBox> </Grid> </Window>
MainWindow.xaml.cs代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp2 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); List<Student> stuList = new List<Student>(); stuList.Add(new Student() { Name = "A", Result = 40 }); stuList.Add(new Student() { Name = "B", Result = 50 }); stuList.Add(new Student() { Name = "C", Result = 60 }); stuList.Add(new Student() { Name = "D", Result = 70 }); stuList.Add(new Student() { Name = "E", Result = 80 }); list.DataContext = new { Model = stuList}; } } public class Student { public string Name { get; set; } public int Result { get; set; } } }
运行结果:
根据学生成绩结果来选择不同的模板展示数据。
标签:stuList,Windows,System,public,new,ItemTemplateSelector,using,WPF,选择器 From: https://www.cnblogs.com/cdaniu/p/16739980.html