Binding Converter : IValueConverter
데이터 바인딩에서 바인딩 값을 변환하기 위하여 사용
1. 기본적인 사용
[ xmal ]
NameSpace정의 - xmal 최상위 태그에 정의
xmlns:src="clr-namespace:ProjectTest.Converters"
Resources에 정의
<src:DateConverter x:Key="dateConverter"/>
xmal에서 converter 사용
<TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,8,0"
Name="startDateTitle"
Style="{StaticResource smallTitleStyle}">Start Date:</TextBlock>
<TextBlock Name="StartDateDTKey" Grid.Row="2" Grid.Column="1"
Text="{Binding Path=StartDate, Converter={StaticResource dateConverter}}"
Style="{StaticResource textStyleTextBlock}"/>
[ cs ]
public class DateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime date = (DateTime)value;
return date.ToShortDateString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value as string;
DateTime resultDateTime;
if (DateTime.TryParse(strValue, out resultDateTime))
{
return resultDateTime;
}
return DependencyProperty.UnsetValue;
}
}
2. Style Converter
[ xmal ]
NameSpace정의 - xmal 최상위 태그에 정의
xmlns:Converters="clr-namespace:ProjectTest.Converters"
Resources에 정의 - 예) UserControl
<UserControl.Resources>
<Converters:StyleConverter x:Key="StyleConverter" />
</UserControl.Resources>
xmal에서 converter 사용
<Control Style="{Binding Path=shape, Converter={StaticResource StyleConverter}, ConverterParameter=DogStyle}" Width="80" Height="80"/>
[ cs ]
public class StyleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ResourceDictionary dic = Application.Current.Resources;
Style returnStyle = new Style();
switch (parameter.ToString())
{
case "DogStyle":
if ((String)value == "dog")
{
returnStyle = dic["dog1"] as Style;
}
else
{
returnStyle = dic["dog2"] as Style;
}
break;
case "CatStyle":
switch ((String)value)
{
case "YellowCat":
returnStyle = dic["YCat"] as Style;
break;
case "RedCat":
returnStyle = dic["RCat"] as Style;
break;
default:
break;
}
break;
}
return returnStyle;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
|