我們經(jīng)常有這樣的需求,給xaml的一個元素綁定一個值,但是顯示用綁定值來顯示其他的值。比如從數(shù)據(jù)庫中取出的日期是2010-11-14,顯示的時候需要顯示2010年11月14日,怎么解決這個需求呢?silverlight給我們提供了一個IValueConverter接口來解決這個問題。
該接口有兩個方法:
Convert:在將源數(shù)據(jù)傳遞到目標(biāo)以在 UI 中顯示之前,對源數(shù)據(jù)進行修改。
ConvertBack:在將目標(biāo)數(shù)據(jù)傳遞到源對象之前,對目標(biāo)數(shù)據(jù)進行修改。此方法僅在 TwoWay 綁定中進行調(diào)用。
我們接下來來實現(xiàn)一個日期的例子:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || value.ToString() == "") return "";
string param = parameter as string;
if (param == "A")
{
try
{ return DateTime.Parse(value.ToString()).ToString("yyyy年MM月dd日"); }
catch
{ throw; }
}
else
{
try
{ return DateTime.Parse(value.ToString()).ToLongTimeString(); }
catch
{ throw; }
}
}
這個方法用到了要在轉(zhuǎn)換器邏輯中使用的可選參數(shù)進行日期的轉(zhuǎn)換。
xaml代碼比較簡單直接貼出來:
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DatePicker Height="23" HorizontalAlignment="Left" Margin="88,52,0,0" Name="datePicker1" VerticalAlignment="Top" Width="120" />
<TextBlock Height="53" HorizontalAlignment="Left" Margin="88,95,0,0" Name="textBlock1" Text="{Binding ElementName=datePicker1, Path=Text,Converter={StaticResource converter}, ConverterParameter=A}" VerticalAlignment="Top" Width="142" />
<TextBlock Height="58" HorizontalAlignment="Left" Margin="88,154,0,0" Name="textBlock2" Text="{Binding ElementName=datePicker1,Path=Text,Converter={StaticResource converter}, ConverterParameter=B}" VerticalAlignment="Top" Width="142" />
</Grid>
運行結(jié)果:
代碼比較簡單,不再贅述,有興趣的同學(xué)可以下載參考:代碼下載