Silverlight DataGrid應用示例(自定義值轉換器和雙向綁定)

在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、本篇結束

轉自:http://blog.csdn.net/xingjunli/archive/2010/02/24/5322377.aspx

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章