在WPF中,决定数据外观的是DataTemplate,即DataTemplate是数据内容的表现形式,一条数据显示成什么样子,是简单的文本还是直观的图形,就是由DataTemplate决定的。
下面通过设计ListBox及ComboBox控件的DataTemplate,把单调的数据显示成直观的柱状图。
<Window x:Class="DataTemplateDemo.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window2" Height="153" Width="300">
<Window.Resources>
<DataTemplate x:Key="MyItem">
<StackPanel Orientation="Horizontal">
<Grid>
<Rectangle Stroke="Yellow" Fill="Orange" Width="{Binding Price}"></Rectangle>
<TextBlock Text="{Binding Year}"></TextBlock>
</Grid>
<TextBlock Text="{Binding Price}"></TextBlock>
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox ItemTemplate="{StaticResource MyItem}" x:Name="listBox1"></ListBox>
<ComboBox ItemTemplate="{StaticResource MyItem}" x:Name="comboBox1"></ComboBox>
</StackPanel>
</Window>
后台代码:
public partial class Window2 : Window
{
public Window2()
{
InitializeComponent();
List<Unit> units = new List<Unit>();
Unit unit1 = new Unit() { Year = "2001", Price=100 };
Unit unit2 = new Unit() { Year = "2002", Price = 120 };
Unit unit3 = new Unit() { Year = "2003", Price = 140 };
Unit unit4 = new Unit() { Year = "2004", Price = 160 };
Unit unit5 = new Unit() { Year = "2005", Price = 180 };
units.Add(unit1);
units.Add(unit2);
units.Add(unit3);
units.Add(unit4);
units.Add(unit5);
listBox1.ItemsSource = units;
comboBox1.ItemsSource = units;
}
}
class Unit
{
public string Year { get; set; }
public int Price { get; set; }
}
效果如下图:
也可以把DataTemplate作用在某个数据类型上,方法是设置DataTemplate的DataType属性。上面的例子也可以通过这种方式实现:
<Window x:Class="DataTemplateDemo.Window3"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplateDemo"
xmlns:c="clr-namespace:System.Collections;assembly=mscorlib"
Title="Window3" Height="153" Width="300">
<Window.Resources>
<DataTemplate DataType="{x:Type local:MyUnit}">
<StackPanel Orientation="Horizontal">
<Grid>
<Rectangle Stroke="Yellow" Fill="Orange" Width="{Binding Price}"></Rectangle>
<TextBlock Text="{Binding Year}"></TextBlock>
</Grid>
<TextBlock Text="{Binding Price}"></TextBlock>
</StackPanel>
</DataTemplate>
<c:ArrayList x:Key="ds">
<local:MyUnit Year = "2001" Price="100"/>
<local:MyUnit Year = "2002" Price="120"/>
<local:MyUnit Year = "2003" Price="140"/>
<local:MyUnit Year = "2004" Price="160"/>
<local:MyUnit Year = "2005" Price="180"/>
</c:ArrayList>
</Window.Resources>
<StackPanel>
<ListBox x:Name="listBox1" ItemsSource="{StaticResource ds}"></ListBox>
<ComboBox x:Name="comboBox1" ItemsSource="{StaticResource ds}"></ComboBox>
</StackPanel>
</Window>
后台代码:
public class MyUnit
{
public string Year { get; set; }
public int Price { get; set; }
}
备注:本例来源于刘铁锰先生的《深入浅出WPF》。