Silverlightカスタムタイプ変換器(またはカスタム変換器)

14372 ワード


  
    
  public class DateTimeConverter : IValueConverter
{
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns></returns>
public object Convert( object value,
Type targetType,
object parameter,
CultureInfo culture)
{
if (value != null && value.ToString().Trim() != "" )
{
DateTime date
= (DateTime)value;
// return date.ToShortDateString();
// return date.ToString("yyyy MM dd HH:mm:ss");
return date.ToString( " yyyy-MM-dd " );
}
else
{
return "" ;
}

}

public object ConvertBack( object value,
Type targetType,
object parameter,
CultureInfo culture)
{
string strValue = value.ToString();
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return value;
}
}



/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns></returns>
public class ConvtoBSfcodeToStr : 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 (value.ToString() == " 01 " ? " " : " " );
}

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() == " " ? " 01 " : " 02 " );
}
}

上には2つのカスタムタイプ変換器があります
XAMLドキュメントでの参照は次のとおりです.
一:DateTimeConverter変換器の使用

  
    
1:
   xmlns:local="clr-namespace:KX_EHR"
>

2:
< UserControl.Resources >
< local:DateTimeConverter x:Key ="DateConverter" />
</ UserControl.Resources >

3:
< TextBlock Text =" {Binding Uoperatedate, Converter={StaticResource DateConverter}} " />

二:ConvtoBSfcodeToStr変換器の使用

  
    
1:
   xmlns:localConv="clr-namespace:KX_EHR.Class"
>

2:
< UserControl.Resources >
< localConv:ConvtoBSfcodeToStr x:Key ="ConverBStoStr" />
</ UserControl.Resources >

3:
< TextBlock Text =" {Binding ,Converter={StaticResource ConverBStoStr}} " />