类型转换器提供字符串文本到值的转换方法来帮助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. Markdown的使用简介

    以前有摘抄过,然而onenote速度感人,现在又主要用Linux,所以在这里备份一下,好方便用 Linux下推荐remakeble软件,或者直接sublime text,再或者vim,反正我不会ema ...

  2. Web Worker

    写在前面 众所周知,JavaScript是单线程的,JS和UI更新共享同一个进程的部分原因是它们之间互访频繁,但由于共享同一个进程也就会造成js代码在运行的时候用户点击界面元素而没有任何响应这样的情况 ...

  3. Apache配置HTTPS功能

    apache配置https 一.yum 安装openssl和openssl-devel,httpd-devel 二.生成证书(也可以从公司的证书颁发机构获取): #建立服务器密钥 openssl ge ...

  4. UVA1213Sum of Different Primes(素数打表 + DP)

    题目链接 题意:选择k个素数,使得和为N(1120)的方案数: 筛选出 <= N 的素数,然后就背包 写的时候没初始dp[0][0] = 1;而且方案数也没相加,真是弱逼 #include &l ...

  5. java编程思想-java中的并发(四)

    五. 新类库中的构件 Java SE5的java.util.concurrent引入了大量设计用来解决并发问题的新类.学习使用它们将有助于编写出更加简单而强壮的并发程序. 1. CountDownLa ...

  6. SimpleDateFormat 12小时制以及24小时制的写法

    有些代码按了复制键没有效果,但是其实已经复制到剪贴板上面了,大家请注意哦! 我的文章有时会稍有修改,转载请注明出处哦! 原文地址:SimpleDateFormat 12小时制以及24小时制的写法 去代 ...

  7. 第5章 jQuery对表单、表格的操作及更多应用

    本章主要是对前面4章的小结和应用. 一. 表单form应用 表单分为3个组成部分 (1)form标签 表单可包含文本域,复选框,单选按钮等等.表单用于向指定的 URL 传递用户数据. (2)表单域 - ...

  8. Codeforces 719B Anatoly and Cockroaches(元素的交叉排列问题)

    题目链接:http://codeforces.com/problemset/problem/719/B 题目大意: 有一队蟑螂用字符串表示,有黑色 ‘b’ 和红色 'r' 两种颜色,你想使这队蟑螂颜色 ...

  9. C++ wMA 算法

    CMakeLists.txt project(aaa) add_library(aaa SHARED aaa.cpp) add_executable(bbb bbb.cpp) target_link_ ...

  10. php瀑布流,把一个数组分4个数组,按照时间排序

    简单介绍:把一个数组分成4个数组,取其中1的倍数 <?php $arr = array( ', ', ', ', ', ', ', ', ', ', ', ', ', ); foreach($a ...