SilverLight学习笔记--关于使用IValueConvert对绑定数据的格式化操作

 在Silverlight中我们经常要用到数据绑定,例如在使用ListBox展现数据时,就需要绑定我们指定的数据源。而在对绑定的数据进行展现时,我们又经常需要对数据的表现形式进行各式各样的处理。
 在Silverlight中我们可以使用IValueConverter 实现绑定数据的格式化。在本文我们将示例如何进行操作:
 一、案例描述:
 我们有一个数据源People,是一个Person类的列表,Person类有两个属性,一个是姓名,一个是年龄。我们需要把People在界面上展示出来。但是在展示时我们需要按不同的年龄段来提示不同的背景。
 下面我们就来具体实现:
 二、案例实现
 打开VS2008,新建项目Silverlight应用程序,名为MyIValueConverter。确定后,系统为我们自动创建了两个项目,一个MyIValueConverter,一个MyIValueConverter.Web。
 1、在MyIValueConverter项目中新建两个类Person和People.代码如下:
                               Person代码
Code
                   People代码
Code

  2、在MyIValueConverter项目中进行Page.xaml界面设计,Page.xaml代码如下:
<UserControl x:Class="MyIValueConverter.Page"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:customer
="clr-namespace:MyIValueConverter"
    Width
="400" Height="300">
    
<Grid x:Name="LayoutRoot" Background="White">
        
<ListBox x:Name="peopleList" >
            
<ListBox.ItemTemplate>
                
<DataTemplate>
                    
<StackPanel x:Name="peopleItem"  Orientation="Horizontal">
                        
<TextBlock x:Name="peopleName" Width="80" Height="30" Text="{Binding Name}"> </TextBlock>
                        
<TextBlock x:Name="peopleAge" Width="80" Height="30" Text="{Binding Age}"></TextBlock>
                    
</StackPanel>
                
</DataTemplate>
            
</ListBox.ItemTemplate>
        
</ListBox>
    
</Grid>
</UserControl>
3、编辑Page.xaml的后台代码,Page.xaml.cs的代码为
Code
按下F5运行,我们可以看到People数据已经显示在我们的ListBox中,但此时它们并没有按年龄段分色显示。
 4、在MyIValueConverter项目中添加新类AgeConverter,此类继承自IValueConverter,在此类我们需要对Age进行分段判断,
然后根据不同的年龄段返回不同的SolidColorBrush对象。AgeConverter类代码如下:
Code
5、在MyIValueConverter中修改其Page.xaml代码,加入如下代码段
     <UserControl.Resources>
        
<customer:AgeConverter x:Key="AgeConvertColor"/>
    
</UserControl.Resources>
修改StackPanel的属性
<StackPanel x:Name="peopleItem"  Orientation="Horizontal" Background="{Binding Age, Converter={StaticResource AgeConvertColor}}">
    把它的Background属性和我们的Person对象的Age值进行了关联,根据不同的年龄段来设置不同的背景色。
   Page.xaml代码如下:
Code

按F5运行可看到不同年龄段的记录在ListBox中显示时具有不同的显示背景。

前往:Silverlight学习笔记清单

 本文参照了部分网络资料,希望能够抛砖引玉,大家共同学习。
(转载本文请注明出处)


posted @ 2009-07-23 11:42  wsdj  阅读(1741)  评论(0编辑  收藏  举报