在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》。