1、iconfont
如上图所示:首先在https://www.iconfont.cn/网址找到如下0---9十个数字的矢量图,添加到项目,下载到本地,找到文件 iconfont.ttf 添加到程序中:
2、建立一个DigitsConverter类进行数据转换
注意:在WPF中阿里矢量图标“
”,通过字段绑定需要写为“\ue000”,否则只显示字符串
public class DigitsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return null;
}
string str = null;
string ledDigit;
foreach (var item in value as string)
{
switch (item)
{
case '0':
ledDigit = "\ue000";//""
break;
case '1':
ledDigit = "\ue001";
break;
case '2':
ledDigit = "\ue002";
break;
case '3':
ledDigit = "\ue003";
break;
case '4':
ledDigit = "\ue004";
break;
case '5':
ledDigit = "\ue005";
break;
case '6':
ledDigit = "\ue006";
break;
case '7':
ledDigit = "\ue007";
break;
case '8':
ledDigit = "\ue008";
break;
case '9':
ledDigit = "\ue009";
break;
case '.':
ledDigit = ".";
//ledDigit = "\ue00d";//小数点转义
break;
default:
ledDigit = $"{item}";
break;
}
str += ledDigit;
}
return str;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
3、前台XAML:
注意:将需要进行数据转换的TextBlock"的属性-FontFamily设置为“iconfont.ttf”路径;如下:FontFamily="../Assets/Fonts/#iconfont"
<Window.DataContext>
<viewmodel:MainWindowViewModel></viewmodel:MainWindowViewModel>
</Window.DataContext>
<Window.Resources>
<commons:DigitsConverter x:Key="DigitsConverter"></commons:DigitsConverter>
</Window.Resources>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal" Margin="0 20">
<TextBlock Text="输入数据:" Foreground="White" FontSize="60"></TextBlock>
<TextBox x:Name="inText" Text="{Binding InputData,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource DigitsConverter}}" FontFamily="../Assets/Fonts/#iconfont" MinWidth="300" FontSize="60" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="输出数据:" Foreground="White" FontSize="60"></TextBlock>
<TextBlock Text="{Binding ElementName=inText,Path=Text}" FontFamily="../Assets/Fonts/#iconfont" Foreground="#00FF00" FontSize="60" Width="auto"></TextBlock>
</StackPanel>
</StackPanel>
4、后台ViewModel
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private string inputData;
public string InputData
{
get { return inputData; }
set
{
inputData = value;
RaisePropertyChanged();
}
}
}
5、最终效果