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.Shapes; namespace TestLoadPic { /// <summary> /// Interaction logic for TestTemplateSelectorWind.xaml /// </summary> public partial class TestTemplateSelectorWind : Window { public TestTemplateSelectorWind() { InitializeComponent(); LoadData(); lb.ItemsSource = list; } public List<Person> list { get; set; } public void LoadData() { Random r = new Random(); list = new List<Person>(); for (int i = 0; i < 10; i++) { int rnd=r.Next(100); string sex="男"; if(rnd>50){ sex="女"; } list.Add(new Person { name = "张三" + i, sex=sex, age = rnd }); } } } public class Person { public string name { get; set; } public int age { get; set; } public string sex { get; set; } } public class MyDataTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { var fe = container as FrameworkElement; var obj = item as Person; DataTemplate dt = null; if (obj != null && fe != null) { if (obj.age > 50) dt = fe.FindResource("one") as DataTemplate; else dt = fe.FindResource("two") as DataTemplate; } return dt; } } }
UI:
<Window x:Class="TestLoadPic.TestTemplateSelectorWind" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestLoadPic" Title="TestTemplateSelectorWind" Height="448.495" Width="547.826"> <Window.Resources> <local:MyDataTemplateSelector x:Key="mydt"></local:MyDataTemplateSelector> <DataTemplate x:Key="one"> <Border BorderThickness="2" BorderBrush="red" Background="AliceBlue"> <StackPanel Orientation="Horizontal" Name="skp" > <TextBlock Text="{Binding name}" Margin="10"></TextBlock> <TextBlock Text="{Binding age}" Margin="10"></TextBlock> <TextBlock Text="{Binding sex}" Margin="10"></TextBlock> </StackPanel> </Border> <DataTemplate.Triggers> <!--男性背景色设置为绿色--> <DataTrigger Value="男" Binding="{Binding Path=sex}"> <Setter TargetName="skp" Property="Background" Value="Green" /> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> <DataTemplate x:Key="two" > <Border BorderThickness="1" BorderBrush="Blue" Background="YellowGreen" Padding="5" > <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding name}" Margin="10"></TextBlock> <TextBlock Text="{Binding age}" Margin="10"></TextBlock> <TextBlock Text="{Binding sex}" Margin="10"></TextBlock> </StackPanel> </Border> </DataTemplate> </Window.Resources> <Grid> <ListBox Name="lb" ItemTemplateSelector="{StaticResource mydt}"> </ListBox> </Grid> </Window>