wpf系统自带了默认的转换器,如图片转换器,文本到数字的转换器等,都是省略的,先看一下下面这个代码:
<Window x:Class="WpfDemo.ConverterDemo"
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:WpfDemo"
mc:Ignorable="d"
FontSize="30"
Title="ConverterDemo" Height="450" Width="800">
<Window.Resources>
<local:IntConverter x:Key="intConverter"/>
</Window.Resources>
<StackPanel HorizontalAlignment="Center">
<TextBlock Text="{Binding Name}"></TextBlock>
<Image Source="{Binding Head}" Width="500"/>
<TextBlock Text="{Binding Age,Converter={StaticResource intConverter}}"></TextBlock>
<TextBox Text="{Binding Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
</Window>
创建ViewModel类:
public class Persion : ViewModelBase
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
OnProertyChanged(nameof(Name));
}
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
OnProertyChanged(nameof(Age));
}
}
private string head;
public string Head
{
get { return head; }
set
{
head = value;
OnProertyChanged(nameof(Head));
}
}
}
窗体后台代码:
public partial class ConverterDemo : Window
{
public ConverterDemo()
{
InitializeComponent();
DataContext = new Persion()
{
Name = "WPF UI",
Age = 18,
Head = "http://n.sinaimg.cn/news/transform/700/w1000h500/20210316/51c0-kmkptxe0299440.jpg"
};
}
}
后台代码中设置了DataContext,在xaml中,第一个textblock的text属性绑定了Name属性,text是string,Name也是string,这个绑定毋庸置疑。
第二个Image的Source绑定了Head属性,这就有些奇怪了,image的Source属性是这样的:
,它不是String类型,为什么绑定到string类型的Head属性上,就可以显示图片呢?这中间就用到了系统默认的转换器了。
下面我们自己创建一个转换器,它将 123 转换成”一二三”等,
public class IntConverter : IValueConverter
{
private Dictionary<int, string> dic = new Dictionary<int, string>
{
{ 0,"零"},
{1, "一"},
{2,"二" },
{3,"三" },
{4, "四"},
{5, "五"},
{6,"六" },
{7,"七" },
{8,"八" },
{9,"九" },
};
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string result = "";
var v = value?.ToString();
if (string.IsNullOrEmpty(v)) return "0";
foreach (var item in v)
{
int.TryParse(item.ToString(), out int ch);
result += dic[ch];
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
转换器继承自 IValueConverter 接口,实现转换方法。当textbox的值输入123时,textblock收到Age改变事件,更新UI时,将123从int类型转换成汉字。再显示到界面上。
就是在ViewModel的数据到达UI之前,要使用Converter处理一下,再交给UI显示。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容