码迷,mamicode.com
首页 > Windows程序 > 详细

WPF:类型转换器的实现

时间:2015-08-20 12:14:27      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:

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

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

 1、MainWindow.xaml

 1 <Window x:Class="WpfApplication1.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:sys="clr-namespace:System;assembly=mscorlib"
 5         xmlns:local="clr-namespace:WpfApplication1"
 6         Title="MainWindow" Height="350" Width="525">
 7     <Window.Resources>
 8         <sys:String x:Key="string1">李白</sys:String>
 9     </Window.Resources>
10     <DockPanel HorizontalAlignment="Left" Height="322" LastChildFill="False" VerticalAlignment="Top" Width="515" Margin="0,0,0,-2">
11         <Button DockPanel.Dock="Left" Background="AliceBlue" Width="264">
12             <local:Book Name="CookBook" Price="$0.1">
13                 内容:梦里花落知多少
14             </local:Book>
15         </Button>
16         <Button DockPanel.Dock="Right" Width="249">
17             <Button.Background>
18                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
19                     <GradientStop Color="Yellow" Offset="0.0"/>
20                     <GradientStop Color="Aquamarine" Offset="0.25"/>
21                     <GradientStop Color="Bisque" Offset="0.75"/>
22                     <GradientStop Color="Coral" Offset="1.0"/>
23                     
24                 </LinearGradientBrush>
25             </Button.Background>
26             Hello XAML
27         </Button>
28     </DockPanel>
29 
30 </Window>

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

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

2、Book.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 //ContenProperty所在的命名空间
 6 using System.Windows.Markup;
 7 
 8 namespace WpfApplication1
 9 {
10     [ContentProperty("Text")] //声明Content属性
11     public class Book
12     {
13         public Book()
14         {
15         }
16         //Name属性
17         public string Name
18         {
19             get;
20             set;
21         }
22         //Price属性的数据类型是一个MoneyType类,该类声明了类型转换器,可以将带有美元符号的价格转换为人民币
23         public MoneyType Price 
24         {
25             get;
26             set;
27         }
28         //Text属性
29         public string Text { get; set; }
30 
31         public override string ToString()
32         {
33             string str = Name + "售价为:" + Price + "元\n"+Text;
34             return str;
35         }
36     }
37 }

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

3、MoneyType.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 //TypeConverter所在的命名空间
 7 using System.ComponentModel;
 8 
 9 namespace WpfApplication1
10 {
11     //声明类型转换器
12     [TypeConverter(typeof(MoneyConverter))]
13     public class MoneyType
14     {
15         private double _value;
16         public MoneyType() { _value = 0; }
17         public MoneyType(double value)
18         {
19             _value = value;
20         }
21         public override string ToString()
22         {
23             return _value.ToString();
24         }
25         //价格转换方法,这里只考虑美元和人民币,不考虑其他币种
26         public static MoneyType Parse(string value)
27         {
28             string str = (value as string).Trim();
29             if (str[0] == $)
30             {
31                 //将美元转换为人民币
32                 string newprice = str.Remove(0, 1);
33                 double price = double.Parse(newprice);
34                 return new MoneyType(price * 8);
35             }
36             else
37             {
38                 //不带特殊符号的字符串默认识别为人民币
39                 double price = double.Parse(str);
40                 return new MoneyType(price);
41             }
42         }
43     }
44 }

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:类型转换器的实现

标签:

原文地址:http://www.cnblogs.com/tt2015-sz/p/4744181.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!