在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