完成效果如下:
主要实现四个转换器:
1. 整型转换为布尔型,如界面第一行数据,输入奇数显示Odd,输入偶数显示Even
2. 布尔类型转字符串,如第二行数据,CheckBox勾选为True,转换显示YES,否则False显示NO
3.字符串转颜色,字符串转图片,选择M,背景标识蓝色,图片显示一个男性图片,选择F,背景标识红色,图像显示为一个女性
实现代码如下:
整型转布尔型为例,添加IntToStringConverter 类
using System.Windows.Data;
namespace _01_Demo
{
public class IntToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.ToString() != "" && int.Parse(value.ToString()) % 2 == 0)
{
return "Even";
}
else if (value.ToString() != "" && int.Parse(value.ToString()) % 2 != 0)
{
return "Odd";
}
else
{
return Binding.DoNothing;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
界面添加资源
<Window.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="50"/>
<Setter Property="Margin" Value="10"/>
</Style>
<local:IntToStringConverter x:Key="Int2ODDEVEN"></local:IntToStringConverter>
</Window.Resources>
<Grid ShowGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox x:Name="txtODDEVEN" FontSize="30" BorderThickness="3" Margin="5"/>
<TextBlock Grid.Column="1" Text="{Binding ElementName=txtODDEVEN,Path=Text,Converter={StaticResource Int2ODDEVEN}}"></TextBlock>
</Grid>
左边文本为输入框,右边文本框绑定左边文本框,指定路径为文本,使用转换器做转换,输入数字理解触发转换。
其它转换类型添加对应类
using System.Windows.Data;
namespace _01_Demo
{
public class BoolToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if((bool)value==true)
{
return "YES";
}
else
{
return "NO";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
界面添加:
<local:BoolToStringConverter x:Key="Bool2YESNO"></local:BoolToStringConverter>
<CheckBox x:Name="chkYESNO" FontSize="30" VerticalAlignment="Center"
Grid.Row="1" Grid.Column="0" Margin="5" Content="Yes/No?"></CheckBox>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding ElementName=chkYESNO,Path=IsChecked}"></TextBlock>
<TextBlock Grid.Column="2" Grid.Row="2" Text="{Binding ElementName=chkYESNO,Path=IsChecked,Converter={StaticResource Bool2YESNO}}"></TextBlock>
网友评论