WPF 范例程序之一 – 数据绑定(Data Binding) – 附源代码下载
本文演示如何采用常用的技术创建WPF 数据绑定应用程序,如ListBox显示产品列表,Image显示产品图片等等,并提供基于VS 2008 的范例程序下载。
首先,看看范例程序的演示界面:
下面介绍范例程序的一些基本要点:
1. 数据源Data Source
基于演示的需要,本范例程序的数据源定义在XAML文件的Resources元素内,实际应用程序则多数从数据库中读取。
<Window.Resources>
<local:ShoppingCart x:Key="Cart">
<local:ShoppingCartItem SKU="460"
Item="多媒体键盘"
Value="65.00"
ShortDescription="全新正品 Hello Kitty 迷你多媒体键盘/USB键盘/超薄键盘"
ProductImage="http://www.giftcenter.cn/giftcenterpictures/img640/04/103/04-103-005.jpg"/>
<local:ShoppingCartItem SKU="461"
Item="不倒翁牙签筒"
Value="8.00"
ShortDescription="Hello Kitty 奇趣蛋型不倒翁牙签筒/牙签罐/牙签盒"
ProductImage="http://www.giftcenter.cn/giftcenterpictures/img640/02/303/02-303-028.jpg"/>
<local:ShoppingCartItem SKU="388"
Item="保健磁化水杯"
Value="29.00"
ShortDescription="Hello Kitty 新款保温保健磁化水杯(陶瓷内胆)"
ProductImage="http://www.giftcenter.cn/giftcenterpictures/img640/02/310/02-310-020.jpg"/>
<local:ShoppingCartItem SKU="242"
Item="眼镜盒"
Value="15.00"
ShortDescription="Hello Kitty 白色皮质眼镜盒(3) 情侣小礼品"
ProductImage="http://www.giftcenter.cn/giftcenterpictures/img640/02/204/02-204-005.jpg"/>
</local:ShoppingCart>
</Window.Resources>
2. 数据绑定ListBox
在本范例程序中,我们绑定ListBox到动态的数据集合中List<ShoppingCartItem>。
<ListBox Grid.Row="1" Grid.ColumnSpan="4" ItemsSource="{Binding}" Grid.RowSpan="1" SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- the outer StackPanel (one per row) -->
<StackPanel Orientation="Horizontal" Width="520">
<!-- the inner stack panels – one per column -->
<StackPanel Orientation="Vertical" Width="40">
<TextBlock Text="{Binding Path=SKU}" />
</StackPanel>
<StackPanel Orientation="Vertical" Width="100">
<TextBlock Text="{Binding Path=Item}" />
</StackPanel>
<StackPanel Orientation="Vertical" Width="330">
<TextBlock Text="{Binding Path=ShortDescription}" />
</StackPanel>
<StackPanel Orientation="Vertical" Width="60">
<TextBlock Text="{Binding Path=Value}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
3. ListBox的SelectionChanged事件
通过选择ListBox中显示的产品列表,触发ListBox的SelectionChanged事件,在对应的方法中,切换产品图片的显示。
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = sender as ListBox;
ShoppingCartItem scItem = lb.SelectedItem as ShoppingCartItem;
// Create Image Element
Image myImage = new Image();
myImage.Width = 500;
// Create source
BitmapImage myBitmapImage = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit();
myBitmapImage.UriSource = new Uri(scItem.ProductImage);
myBitmapImage.DecodePixelWidth = 500;
myBitmapImage.EndInit();
ProductImage.Source = myBitmapImage;
}
范例程序运行环境:Visual Studio 2008 SP1。如果你对XAML不熟悉,建议你参考如下XAML学习笔记系列: