MSDN的解释:
提供一种根据数据对象和与该数据绑定的元素来选择数据模板 DataTemplate 的方法。
示例代码:
<Window x:Class="WpfApplication1.Window2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="Window2" Height="300" Width="300" Loaded="Window2_OnLoaded"> <Window.Resources> <DataTemplate x:Key="T1"> <TextBlock Text="{Binding}" Background="DarkBlue" Foreground="White" Padding="10,0"></TextBlock> </DataTemplate> <DataTemplate x:Key="T2"> <TextBlock Text="{Binding}" Background="DarkCyan" Foreground="White" Padding="10,0"></TextBlock> </DataTemplate> <local:CTemplateSelector x:Key="TS"></local:CTemplateSelector> </Window.Resources> <Grid> <ListBox x:Name="Lbox" ItemTemplateSelector="{StaticResource TS}"></ListBox> </Grid> </Window>
public partial class Window2 : Window { public Window2() { InitializeComponent(); } private void Window2_OnLoaded(object sender, RoutedEventArgs e) { var source = new List<string> { "1","2","3","4" }; this.Lbox.ItemsSource = source; } }
public class CTemplateSelector:DataTemplateSelector { public override DataTemplate SelectTemplate( object item, DependencyObject container ) { if (item == null) throw new ArgumentNullException("item"); var element = container as FrameworkElement; if ( element != null ) { var str = item.ToString(); int val; if (int.TryParse(str, out val)) { if (val%2 == 0) { return element.FindResource("T1") as DataTemplate; } else { return element.FindResource( "T2" ) as DataTemplate; } } } return base.SelectTemplate(item, container); } }
这个示例就是在一个 ListBox 控件中实现隔行换色的功能,当然也可以通过其他方法实现。
运行结果:
参考:
http://msdn.microsoft.com/zh-cn/library/system.windows.controls.datatemplateselector%28v=vs.110%29.aspx