类型转换器提供字符串文本到值的转换方法来帮助WPF设计时在XAML中配置属性。具体用法可以参考MSDN的文档:如何:实现类型转换器

下面是一个Demo,参考自<葵花宝典--WPF自学手册>。

1、MainWindow.xaml

 <Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="" Width="">
<DockPanel HorizontalAlignment="Left" Height="" LastChildFill="False" VerticalAlignment="Top" Width="" Margin="0,0,0,-2">
<Button DockPanel.Dock="Left" Background="AliceBlue" Width="">
<local:Book Name="CookBook" Price="$0.1">
内容:梦里花落知多少
</local:Book>
</Button>
<Button DockPanel.Dock="Right" Width="">
<Button.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
<GradientStop Color="Yellow" Offset="0.0"/>
<GradientStop Color="Aquamarine" Offset="0.25"/>
<GradientStop Color="Bisque" Offset="0.75"/>
<GradientStop Color="Coral" Offset="1.0"/> </LinearGradientBrush>
</Button.Background>
Hello XAML
</Button>
</DockPanel> </Window>

第一个Button的Content属性的值设置成一个自定义的Book类,该Book对象调用ToString()方法返回的字符串就会显示在Button上,注意该Book对象的Price属性设置为"$0.1",即0.1美元,通过类型转换器,将会把这个值转换为"0.8"(人民币)。

第二个Button使用了渐变画刷来设置背景。

2、Book.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//ContenProperty所在的命名空间
using System.Windows.Markup; namespace WpfApplication1
{
[ContentProperty("Text")] //声明Content属性
public class Book
{
public Book()
{
}
//Name属性
public string Name
{
get;
set;
}
//Price属性的数据类型是一个MoneyType类,该类声明了类型转换器,可以将带有美元符号的价格转换为人民币
public MoneyType Price
{
get;
set;
}
//Text属性
public string Text { get; set; } public override string ToString()
{
string str = Name + "售价为:" + Price + "元\n"+Text;
return str;
}
}
}

Book类中声明了三个自动属性,其中将Text属性声明为ContentProperty,这样不必使用Property-Element语法就可以直接成为Button元素的子类;Price属性是MoneyType类型,该类声明了一个类型转换器,可以将美元转换为人民币。

3、MoneyType.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//TypeConverter所在的命名空间
using System.ComponentModel; namespace WpfApplication1
{
//声明类型转换器
[TypeConverter(typeof(MoneyConverter))]
public class MoneyType
{
private double _value;
public MoneyType() { _value = ; }
public MoneyType(double value)
{
_value = value;
}
public override string ToString()
{
return _value.ToString();
}
//价格转换方法,这里只考虑美元和人民币,不考虑其他币种
public static MoneyType Parse(string value)
{
string str = (value as string).Trim();
if (str[] == '$')
{
//将美元转换为人民币
string newprice = str.Remove(, );
double price = double.Parse(newprice);
return new MoneyType(price * );
}
else
{
//不带特殊符号的字符串默认识别为人民币
double price = double.Parse(str);
return new MoneyType(price);
}
}
}
}

MoneyType类中声明了类型转换器,并且实现了一个类方法Parse(),在该方法中完成对字符串的转换。

4、MoneyConverter.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//TypeConverter所在的命名空间
using System.ComponentModel; namespace WpfApplication1
{ public class MoneyConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
} //转换为字符串类型其实不需要重写此方法
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
{
return true;
}
return base.CanConvertTo(context, destinationType);
} //将string转换为MoneyType
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
return MoneyType.Parse((string)value);
return base.ConvertFrom(context, culture, value); }
//将MoneyType转换为string
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
return ((MoneyType)value).ToString(); }
return base.ConvertTo(context, culture, value, destinationType);
}
}
}

这个类型转换器实现了string和MoneyType的相互转换。

5、运行效果

WPF:类型转换器的实现的更多相关文章

  1. [No000012C]WPF(4/7)类型转换器和标记扩展[译]

    介绍 之前讨论了WPF的基础架构,然后逐步开始学习布局面板,转换,介绍了不同的控件,容器,UI转换等.在这篇文章中,我将讨论每个创建XAML应用前的开发人员应该了解的关于XAML最重要的东西. 标记扩 ...

  2. wpf中xaml的类型转换器与标记扩展

    原文:wpf中xaml的类型转换器与标记扩展 这篇来讲wpf控件属性的类型转换器 类型转换器 类型转换器在asp.net控件中已经有使用过了,由于wpf的界面是可以由xaml组成的,所以标签的便利也需 ...

  3. Spring MVC类型转换器

    类型转换器引入 为什么页面上输入"12",可以赋值给Handler方法对应的参数?这是因为框架内部帮我们做了类型转换的工作.将String转换成int 但默认类型转换器并不是可以将 ...

  4. SpringMVC类型转换器、属性编辑器

    对于MVC框架,参数绑定一直觉得是很神奇很方便的一个东西,在参数绑定的过程中利用了属性编辑器.类型转换器 参数绑定流程 参数绑定:把请求中的数据,转化成指定类型的对象,交给处理请求的方法 请求进入到D ...

  5. 8.Struts2类型转换器

    类型转换器1.引入在Struts2中,请求参数类型不仅可以是String,还可以是其它类型.如,定义一个请求参数birthday为Date类型,给其赋值为1949-10-1,则birthday接收到的 ...

  6. 【Java EE 学习 35 上】【strus2】【类型转换器】【struts2和Servlet API解耦】【国际化问题】【资源文件乱码问题已经解决】

    一.类型转换器 1.在动作类action中,声明和表单中name属性的值同名的属性,提供get和set方法,struts2就可以通过反射机制,从页面中获取对应的内容 package com.kdyzm ...

  7. Struts2:类型转换器

    常规的String,int能自动转换,但是,有些类型不是这么简单,比如输入字符串,但需要Date.自定义类型,因此需要自定义类型转换类型转换器分全局和局部按惯例,局部的优先级高于全局 需求: 1.输入 ...

  8. struts2学习笔记之十一:struts2的类型转换器

    Struts2的类型转换器   如何实现Struts2的类型转换器? * 继承StrutsTypeConverter * 覆盖convertFromString和convertToString   注 ...

  9. Struts2框架的自定义类型转换器

    前言:对于java的基本数据类型及一些系统类(如Date类.集合类),Struts2提供了内置类型转换功能,但是也有一定的限制.所以就演示出自定义类型转换器 一.应用于局部类型转换器 eg.用户登录出 ...

随机推荐

  1. TypeScript Basic Types(基本类型)

    在学习TypeScript之前,我们需要先知道怎么才能让TypeScript写的东西正确的运行起来.有两种方式:使用Visual studio 和使用 NodeJs. 这里我选择的是NodeJs来编译 ...

  2. POJ 2828 Buy Tickets(线段树 树状数组/单点更新)

    题目链接: 传送门 Buy Tickets Time Limit: 4000MS     Memory Limit: 65536K Description Railway tickets were d ...

  3. TCP/IP --- UDP Broadcast Address

    Related information link : 百度百科---->广播地址 Use restrictions: 1. You can only broadcast on the same ...

  4. mac系统的一些操作常识

    mac系统如何显示和隐藏文件 苹果Mac OS X操作系统下,隐藏文件是否显示有很多种设置方法,最简单的要算在Mac终端输入命令.显示/隐藏Mac隐藏文件命令如下(注意其中的空格并且区分大小写): 显 ...

  5. SQL ALTER TABLE 语句在项目中的使用

    1.在实际的项目开发过程中,之前已经创建好的实体类可能需要增加/删除字段,亦或是更改已有字段的属性,比如主键的增长策略从自增型改为UUID型,那么就会涉及到 SQL 中 alter table 语句的 ...

  6. 导出excel失败,提醒提示加载类型库/DDL出错

    导出excel失败,提醒提示加载类型库/DDL出错 www.MyException.Cn   发布于:2012-08-17 02:08:34   浏览:1538次   导出excel失败,提示提示加载 ...

  7. 10月21上午PHP基础

    新建的php文件必须要放在wamp安装目录下的www文件夹里.如果拿到别的地方,php无法运行,将显示错误. <?php?> //嵌入php的方式 <?php //嵌入php方式的开 ...

  8. Java排序算法——插入排序

    import java.util.Arrays; //================================================= // File Name : Select_S ...

  9. Java关键字——super

    使用super关键字可以从子类中调用父类中的构造方法.普通方法和属性 与this调用构造方法的要求一样,语句必须放在子类构造方法的首行 this和super都可以调用构造方法,但是两者不能同时出现,调 ...

  10. Linux 命令小记

    1. pidof 进程名 :获取进程的pid,例如 pidof memcached 得到5333 2. unset Shell变量 :取消设置一个shell变量,从内存和shell的导出环境中删除它, ...