一般,若是有多個 DataTemplate 可用於同一類型的對象,而且您但願根據每一個數據對象的屬性提供本身的邏輯來選擇要應用的 DataTemplate,則應建立 DataTemplateSelector。請注意,若是具備不一樣類型的對象,則能夠對 DataTemplate 設置 DataType 屬性。若是您執行了此操做,則無需建立 DataTemplateSelector。此外,若是對象類型相同但屬性不一樣,也能夠考慮使用 DataTrigger 或數據轉換器。
通俗講,就是根據不一樣的數據選擇不一樣的模板。接下來,我用一個例子來說述DataTemplateSelector和動態綁定的使用方法。dom
下面例子如圖,只要年齡大於50的使用一種模板,不然另外一種模板,並在年齡大於50的模板中是男性的添加觸發器使用背景變成藍色的。ide
一、建立模板選擇器spa
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; } }
二、界面設計:設計
<Window x:Class="WpfApplication5.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication5" Title="MainWindow" Height="350" Width="525"> <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="CornflowerBlue" /> </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>
三、後臺:code
public partial class MainWindow : Window { public MainWindow() { 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++) { list.Add(new Person { name = "張三" + i, age = r.Next(100) }); } } } public class Person { public string name { get; set; } public int age { get; set; } }