自定义值转换器和双向绑定

 在Silverlight中可以使用如“Binding="{Binding Name}"的方式将数据同XAML中的控件进行绑定将它格式化我们需要的样子;使用这个的方法在SL中可以方便的对集合对像、XML文件,WCF服务,数据表、自定义对象等进行数据绑定;
    在平时的开发过程中我们可能会碰到源数据是一个数值(0,1),或者是一个Boolean(true、false)值;当我们最终显示时确希望显示为(男、女)或者(借、贷)等描述信息时下面的DEMO对你就有用了;
    1、先介绍 Binding.Converter 属性,主要用于在数据绑定时调用自定义转换器将不兼容的数据类型转换成我们需要的数据类型,相当于架起两个不同数据类型转换的桥梁;官方解释:获取或设置转换器对象,当数据在源和目标之间(或相反方向)传递时,绑定引擎调用该对象来修改数据。参考 : http://msdn.microsoft.com/zh-cn/library/system.windows.data.binding.converter(VS.95).aspx
    2、DEMO最终效果:
http://hi.csdn.net/attachment/201002/24/2243869_1266987549AqMq.jpg
   3、实现步骤
       3.1自定义类型转器(实现IValueConverter接口Convert和ConvertBack方法)如:
    
  1. public class SexConverter : IValueConverter  
  2.      {  
  3.   public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  4.   {  
  5.       if (targetType != typeof(String)) throw new InvalidOperationException("The target must be a integer!");  
  6.       return (((int)value) == 0 ? "女" : "男");  
  7.   }  
  8.   
  9.   public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  10.   {  
  11.       if (targetType != typeof(Int32)) throw new InvalidOperationException("The target must be a String!");  
  12.       return (value.ToString() == "女" ? 0 : 1);  
  13.   }  
  14.   
  15.      }  
     

     3.2、在Application.Resources引入类型转化器如:

  1. <UConvert:SexConverter x:Key="sexConvert" />  
 

     3.3、在数据绑定中应用转器如:
  

  1. <data:DataGridTextColumn Header="性别" Binding="{Binding Sex, Converter={StaticResource sexConvert},Mode=TwoWay}" />  
   
   4、完整体代码:
       4.1、APP.xaml文件代码:
 
  1. <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  2.        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  3.        x:Class="LoadSilverlight.App"  
  4.        xmlns:UConvert="clr-namespace:LoadSilverlight"  
  5.        >  
  6.      <Application.Resources>  
  7.   <UConvert:SexConverter x:Key="sexConvert" />  
  8.   <UConvert:LoanConverter x:Key="loanConvert" />  
  9.      </Application.Resources>  
  10.  </Application>  
 

       4.2、所有CS代码:
  

  1. namespace LoadSilverlight  
  2.   {  
  3.       public partial class UConverterDemo : UserControl  
  4.       {  
  5.    public UConverterDemo()  
  6.    {  
  7.        InitializeComponent();  
  8.        this.Loaded += new RoutedEventHandler(UConverterDemo_Loaded);  
  9.        List<DataItem> datas = new List<DataItem>();  
  10.        datas.Add(new DataItem { Sex = 0, Loan = true, Name = "jack" });  
  11.        datas.Add(new DataItem { Sex = 1, Loan = true, Name = "lily" });  
  12.        datas.Add(new DataItem { Sex = 0, Loan = false, Name = "Jessica" });  
  13.   
  14.        this.dataGrid.ItemsSource = datas;  
  15.    }  
  16.   
  17.    void UConverterDemo_Loaded(object sender, RoutedEventArgs e)  
  18.    {  
  19.          
  20.    }  
  21.       }  
  22.  
  23.       #region 自定义值转换器   
  24.       public class SexConverter : IValueConverter  
  25.       {  
  26.    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  27.    {  
  28.        if (targetType != typeof(String)) throw new InvalidOperationException("The target must be a integer!");  
  29.        return (((int)value) == 0 ? "女" : "男");  
  30.    }  
  31.   
  32.    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  33.    {  
  34.        if (targetType != typeof(Int32)) throw new InvalidOperationException("The target must be a String!");  
  35.        return (value.ToString() == "女" ? 0 : 1);  
  36.    }  
  37.       }  
  38.   
  39.       public class LoanConverter : IValueConverter  
  40.       {  
  41.    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  42.    {  
  43.        if (targetType != typeof(object)) throw new InvalidOperationException("The target must be a String!");  
  44.        return (((bool)value) == true ? "借" : "贷");  
  45.    }  
  46.    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)  
  47.    {  
  48.        if (targetType != typeof(Boolean)) throw new InvalidOperationException("The target must be a String!");  
  49.        return (value.ToString() == "借" ? true : false);  
  50.    }  
  51.       }  
  52.       #endregion   
  53.   
  54.   
  55.       /// <summary>   
  56.       /// 自定义数据实体   
  57.       /// </summary>   
  58.       public class DataItem  
  59.       {  
  60.    private int _sex;  
  61.    private bool _loan;  
  62.    public int Sex  
  63.    {  
  64.        get { return _sex; }  
  65.        set  
  66.        {  
  67.     _sex = value;  
  68.     onSexChanged("SEX");  
  69.        }  
  70.    }  
  71.    public bool Loan  
  72.    {  
  73.        get { return _loan; }  
  74.        set  
  75.        {  
  76.     _loan = value;  
  77.     onSexChanged("LOAN");  
  78.        }  
  79.    }  
  80.    public String Name { getset; }  
  81.    public event PropertyChangedEventHandler SexChanged;  
  82.    public event PropertyChangedEventHandler LoanChanged;  
  83.   
  84.   
  85.    //双向绑定时属性改变时调用的事件   
  86.    protected void onSexChanged(String sex)  
  87.    {  
  88.        if (SexChanged != null)  
  89.        {  
  90.     SexChanged(thisnew PropertyChangedEventArgs(sex));  
  91.        }  
  92.    }  
  93.    protected void onLoanChanged(String loan)  
  94.    {  
  95.        LoanChanged(thisnew PropertyChangedEventArgs(loan));  
  96.    }  
  97.       }  
  98.   }  
  99.    

      4.3、XAML页完整体代码:
  

  1. <UserControl x:Class="LoadSilverlight.UConverterDemo"  
  2.       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  3.       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  4.       xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  
  5.       Width="400" Height="300">  
  6.       <UserControl.Resources>  
  7.      <!--也可以在这里引用自定义转换器,推荐在全局APP.xaml引用-->  
  8.       </UserControl.Resources>  
  9.       <Grid x:Name="LayoutRoot" Background="White">  
  10.    <data:DataGrid Grid.Row="0" x:Name="dataGrid" Margin="3,3,3,3" AutoGenerateColumns="False">  
  11.        <data:DataGrid.Columns>  
  12.     <data:DataGridTextColumn Header="姓名" Binding="{Binding Name}" IsReadOnly="True" />  
  13.     <data:DataGridTextColumn Header="性别" Binding="{Binding Sex, Converter={StaticResource sexConvert},Mode=TwoWay}" />  
  14.     <data:DataGridTemplateColumn Header="借贷情况">  
  15.         <data:DataGridTemplateColumn.CellTemplate>  
  16.      <DataTemplate>  
  17.          <CheckBox IsChecked="{Binding Loan,Mode=TwoWay}" Content="{Binding Loan, Converter={StaticResource loanConvert}}"/>  
  18.      </DataTemplate>  
  19.         </data:DataGridTemplateColumn.CellTemplate>  
  20.   
  21.     </data:DataGridTemplateColumn>  
  22.        </data:DataGrid.Columns>  
  23.    </data:DataGrid>  
  24.       </Grid>  
  25.   </UserControl>  
  26.   
  27.    

5、本篇结束

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值