我的理解,就是关于一个参数的另一种表现形式,比如你需要把属性值修改为另一种状态,比如1,0 修改成打开与关闭状态类似。
WPF中, 提供一种数据转换的接口、那就是在 System.Windows.Data 命名空间下的,IValueConverter 接口, 该接口的Convert方法可以任意的数据转换操作。
为了更够简单的描述其作用, 在后台声明一个int类型为 Status的变量, 然后通过绑定的形式关联的界面层。( 如下创建MainViewModel层,主要用于关联DataContext )
声明一个 StatusConverter 转换器 , 改转换器实现了,将数据 0 设置为未完成, 为1 则设置为完成。
使用步骤:需要先写一个操作类来继承 IValueConverter
public class StatusConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && int.TryParse(value.ToString(), out int result))
{
if (result == 1)
{
return "完成";
}
}
return "未完成";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Xaml界面数据的操作
<Window x:Class="WpfApp4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp4"
xmlns:converter="clr-namespace:WpfApp4.Converter"<!引入的操作类地址!>
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<converter:StatusConverter x:Key="StatusConverter"/>*<!定义key值!>*
<Style x:Key="TextBlockStyle" TargetType="{x:Type TextBlock}">
<Setter Property="TextWrapping" Value="NoWrap"/>
<Setter Property="TextTrimming" Value="None"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="FontSize" Value="25"/>
</Style>
</Window.Resources>
<Grid>
<UniformGrid Rows="2" Columns="2" >
<TextBlock Text="没有使用转换器的效果:" Style="{DynamicResource TextBlockStyle}" />
<TextBlock Text="{Binding Status}" Style="{DynamicResource TextBlockStyle}"/>
<TextBlock Text="使用转换器的效果:" Style="{DynamicResource TextBlockStyle}"/>
<TextBlock Text="{Binding Status,Converter={StaticResource StatusConverter}}" Style="{DynamicResource TextBlockStyle}"/>~~<!引用Key,自动讲返回的属性值转换为对应的数据!>~~
</UniformGrid>
</Grid>
</Window>
关于IValueConverter 转换器的一部分说明:
//
// 摘要:
// 转换值。
//
// 参数:
// value:
// 绑定源生成的值。
//
// targetType:
// 绑定目标属性的类型。
//
// parameter:
// 要使用的转换器参数。
//
// culture:
// 要用在转换器中的区域性。
//
// 返回结果:
// 转换后的值。 如果该方法返回 null,则使用有效的 null 值。
object Convert(object value, Type targetType, object parameter, CultureInfo culture);
其中
object parameter --参数可以设定标记条件进行判断 对应值:在xaml下的数据为:
<TextBlock FontSize="30" Foreground="#378CE7" Text="{Binding GetYunyinshangZiti, Converter={StaticResource StringToIcon},ConverterParameter=11}" FontFamily="../Fonts/MyFonts/#iconfont">
设定为: Text=“{Binding GetYunyinshangZiti, Converter={StaticResource StringToIcon},ConverterParameter=11}”
使用绑定获取到当前“GetYunyinshangZiti”属性的值,
然后转换器设定为
Converter={StaticResource StringToIcon}
传参是:ConverterParameter=11 — object parameter