在Silverlight中每一个控件都有DataTemplate类型的属性。那么DataTemplate到底有什么作用呢?MSDN上的解释是“用来描述数据对象的可视结构。通常使用 DataTemplate 指定数据的直观表示”。 可能单从字面上的理解起来不是很容易,下面用ListBox的两个案例来诠释一下DataTemplate的作用。
首先,在界面上拖一个ListBox,直接给ListBox的ItemsSource属性赋上一个集合。
<Grid x:Name="LayoutGrid" Background="White">
<ListBox x:Name="list"/>
</Grid>
this.Loaded += (s, e) =>
{
this.list.ItemsSource = new List<Test>()
{
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
new Test { A = "A", B = "B", Text = "显示了", Color = Colors.Red.ToString() },
};
};
从上面的例子我们看到,ListBox直接把集合中每一个Test对象ToString()后显示出来。在 ListBox中的ItemTemplate属性是用来设置每一个ListBoxItem的数据可视化显示,其数据类型是DataTemplate类型。下面,为ListBox编写数据可视化结构模板DataTemplate。
<UserControl.Resources>
<Style TargetType="Ellipse" x:Key="EllipseStyle" >
<Setter Property="Height" Value="10"/>
<Setter Property="Width" Value="10"/>
<Setter Property="Fill" Value="Red"/>
<Setter Property="Stroke" Value="Black"/>
<Setter Property="StrokeThickness" Value="1"/>
<Setter Property="Margin" Value="0,0,5,0"/>
</Style>
<DataTemplate x:Key="ListBoxItemStyle">
<StackPanel x:Name="LayoutSP" Orientation="Horizontal">
<TextBlock Text="测试绑定1:"/>
<TextBlock Text="{Binding A}"/>
<TextBlock Text=";测试绑定2:"/>
<TextBlock Text="{Binding B}"/>
<TextBlock Text=";测试CheckBox:"/>
<CheckBox x:Name="chk">
<StackPanel Orientation="Horizontal" >
<Ellipse Style="{StaticResource EllipseStyle}" Fill="{Binding Color}"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</CheckBox>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutGrid" Background="White">
<ListBox x:Name="list" ItemTemplate="{StaticResource ListBoxItemStyle}"/>
</Grid>
从上面的例子发现,集合中每一个对象的属性值,都按照DataTemplate的模板格式显示出来了。从上面两个例子,已经很直观的说明了DataTemplate的含义了。
Datatemplate在使用时,应注意以下几点:
1.Silverlight中的DataTemplate为编码的最小单元,无法用托管代码改变。
2.DataTemplate只能用Xaml创建,如果一定要用代码动态创建DataTemplate,只好用 XamlLoader.Load(XamlString)的方法来创建.
3.不能引用当前控件的资源,只能引用全局资源
4.不能动态的绑定事件。