在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最终效果:
3、实现步骤
3.1自定义类型转器(实现IValueConverter接口Convert和ConvertBack方法)如:
- public class SexConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(String)) throw new InvalidOperationException("The target must be a integer!");
- return (((int)value) == 0 ? "女" : "男");
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(Int32)) throw new InvalidOperationException("The target must be a String!");
- return (value.ToString() == "女" ? 0 : 1);
- }
- }
3.2、在Application.Resources引入类型转化器如:
- <UConvert:SexConverter x:Key="sexConvert" />
3.3、在数据绑定中应用转器如:
- <data:DataGridTextColumn Header="性别" Binding="{Binding Sex, Converter={StaticResource sexConvert},Mode=TwoWay}" />
4、完整体代码:
4.1、APP.xaml文件代码:
- <Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- x:Class="LoadSilverlight.App"
- xmlns:UConvert="clr-namespace:LoadSilverlight"
- >
- <Application.Resources>
- <UConvert:SexConverter x:Key="sexConvert" />
- <UConvert:LoanConverter x:Key="loanConvert" />
- </Application.Resources>
- </Application>
4.2、所有CS代码:
- namespace LoadSilverlight
- {
- public partial class UConverterDemo : UserControl
- {
- public UConverterDemo()
- {
- InitializeComponent();
- this.Loaded += new RoutedEventHandler(UConverterDemo_Loaded);
- List<DataItem> datas = new List<DataItem>();
- datas.Add(new DataItem { Sex = 0, Loan = true, Name = "jack" });
- datas.Add(new DataItem { Sex = 1, Loan = true, Name = "lily" });
- datas.Add(new DataItem { Sex = 0, Loan = false, Name = "Jessica" });
- this.dataGrid.ItemsSource = datas;
- }
- void UConverterDemo_Loaded(object sender, RoutedEventArgs e)
- {
- }
- }
- #region 自定义值转换器
- public class SexConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(String)) throw new InvalidOperationException("The target must be a integer!");
- return (((int)value) == 0 ? "女" : "男");
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(Int32)) throw new InvalidOperationException("The target must be a String!");
- return (value.ToString() == "女" ? 0 : 1);
- }
- }
- public class LoanConverter : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(object)) throw new InvalidOperationException("The target must be a String!");
- return (((bool)value) == true ? "借" : "贷");
- }
- public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- if (targetType != typeof(Boolean)) throw new InvalidOperationException("The target must be a String!");
- return (value.ToString() == "借" ? true : false);
- }
- }
- #endregion
- /// <summary>
- /// 自定义数据实体
- /// </summary>
- public class DataItem
- {
- private int _sex;
- private bool _loan;
- public int Sex
- {
- get { return _sex; }
- set
- {
- _sex = value;
- onSexChanged("SEX");
- }
- }
- public bool Loan
- {
- get { return _loan; }
- set
- {
- _loan = value;
- onSexChanged("LOAN");
- }
- }
- public String Name { get; set; }
- public event PropertyChangedEventHandler SexChanged;
- public event PropertyChangedEventHandler LoanChanged;
- //双向绑定时属性改变时调用的事件
- protected void onSexChanged(String sex)
- {
- if (SexChanged != null)
- {
- SexChanged(this, new PropertyChangedEventArgs(sex));
- }
- }
- protected void onLoanChanged(String loan)
- {
- LoanChanged(this, new PropertyChangedEventArgs(loan));
- }
- }
- }
4.3、XAML页完整体代码:
- <UserControl x:Class="LoadSilverlight.UConverterDemo"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
- Width="400" Height="300">
- <UserControl.Resources>
- <!--也可以在这里引用自定义转换器,推荐在全局APP.xaml引用-->
- </UserControl.Resources>
- <Grid x:Name="LayoutRoot" Background="White">
- <data:DataGrid Grid.Row="0" x:Name="dataGrid" Margin="3,3,3,3" AutoGenerateColumns="False">
- <data:DataGrid.Columns>
- <data:DataGridTextColumn Header="姓名" Binding="{Binding Name}" IsReadOnly="True" />
- <data:DataGridTextColumn Header="性别" Binding="{Binding Sex, Converter={StaticResource sexConvert},Mode=TwoWay}" />
- <data:DataGridTemplateColumn Header="借贷情况">
- <data:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <CheckBox IsChecked="{Binding Loan,Mode=TwoWay}" Content="{Binding Loan, Converter={StaticResource loanConvert}}"/>
- </DataTemplate>
- </data:DataGridTemplateColumn.CellTemplate>
- </data:DataGridTemplateColumn>
- </data:DataGrid.Columns>
- </data:DataGrid>
- </Grid>
- </UserControl>
5、本篇结束
转自:http://blog.csdn.net/xingjunli/archive/2010/02/24/5322377.aspx