wpf-DataTemplate应用

在WPF中,决定数据外观的是DataTemplate,即DataTemplate是数据内容的表现形式,一条数据显示成什么样子,是简单的文本还是直观的图形,就是由DataTemplate决定的。
下面通过设计ListBox及ComboBox控件的DataTemplate,把单调的数据显示成直观的柱状图。

 1 <Window x:Class="WpfDataTemplate.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         Title="MainWindow" Height="350" Width="525">
 5     <Window.Resources>
 6         <DataTemplate x:Key="MyItem">
 7             <StackPanel Orientation="Horizontal">
 8                 <Grid>
 9                     <Rectangle Stroke="Yellow" Fill="Orange" Width="{Binding Price}"></Rectangle>
10                     <TextBlock Text="{Binding Year}"></TextBlock>
11                 </Grid>
12                 <TextBlock Text="{Binding Price}"></TextBlock>
13             </StackPanel>
14         </DataTemplate>
15     </Window.Resources>
16     
17     <StackPanel>
18         <ListBox ItemTemplate="{StaticResource MyItem}" x:Name="listBox1"></ListBox>
19         <ComboBox ItemTemplate="{StaticResource MyItem}" x:Name="comboBox1"></ComboBox>
20     </StackPanel>
21 </Window>


后台代码:

 1 namespace WpfDataTemplate
 2 {
 3     /// <summary>
 4     /// Interaction logic for MainWindow.xaml
 5     /// </summary>
 6     public partial class MainWindow : Window
 7     {
 8         public MainWindow()
 9         {
10             InitializeComponent();
11 
12             List<Unit> units = new List<Unit>();
13             Unit unit1 = new Unit() { Year = "2001", Price = 100 };
14             Unit unit2 = new Unit() { Year = "2002", Price = 120 };
15             Unit unit3 = new Unit() { Year = "2003", Price = 140 };
16             Unit unit4 = new Unit() { Year = "2004", Price = 160 };
17             Unit unit5 = new Unit() { Year = "2005", Price = 180 };
18             units.Add(unit1);
19             units.Add(unit2);
20             units.Add(unit3);
21             units.Add(unit4);
22             units.Add(unit5);
23 
24             listBox1.ItemsSource = units;
25             comboBox1.ItemsSource = units;
26         }
27     }
28 
29     public class Unit
30     {
31         public string Year { get; set; }
32         public int Price { get; set; }
33     }
34 }
原文地址:https://www.cnblogs.com/zy-style/p/3443245.html