wpf-DataTemplate应用

本文介绍如何在WPF应用中利用DataTemplate技术将数据转换为直观的柱状图展示方式,通过设计ListBox及ComboBox控件的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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值