• WPF:类型转换器的实现


    类型转换器提供字符串文本到值的转换方法来帮助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      <DockPanel HorizontalAlignment="Left" Height="322" LastChildFill="False" VerticalAlignment="Top" Width="515" Margin="0,0,0,-2">
     8         <Button DockPanel.Dock="Left" Background="AliceBlue" Width="264">
     9             <local:Book Name="CookBook" Price="$0.1">
    10                 内容:梦里花落知多少
    11             </local:Book>
    12         </Button>
    13         <Button DockPanel.Dock="Right" Width="249">
    14             <Button.Background>
    15                 <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
    16                     <GradientStop Color="Yellow" Offset="0.0"/>
    17                     <GradientStop Color="Aquamarine" Offset="0.25"/>
    18                     <GradientStop Color="Bisque" Offset="0.75"/>
    19                     <GradientStop Color="Coral" Offset="1.0"/>
    20                     
    21                 </LinearGradientBrush>
    22             </Button.Background>
    23             Hello XAML
    24         </Button>
    25     </DockPanel>
    26 
    27 </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 + ""+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、运行效果

  • 相关阅读:
    leetcode 155. Min Stack 、232. Implement Queue using Stacks 、225. Implement Stack using Queues
    leetcode 557. Reverse Words in a String III 、151. Reverse Words in a String
    leetcode 153. Find Minimum in Rotated Sorted Array 、154. Find Minimum in Rotated Sorted Array II 、33. Search in Rotated Sorted Array 、81. Search in Rotated Sorted Array II 、704. Binary Search
    leetcode 344. Reverse String 、541. Reverse String II 、796. Rotate String
    leetcode 162. Find Peak Element
    leetcode 88. Merge Sorted Array
    leetcode 74. Search a 2D Matrix 、240. Search a 2D Matrix II
    Android的API版本和名称对应关系
    spring 定时任务执行两次解决办法
    解析字符串为泛型的方法
  • 原文地址:https://www.cnblogs.com/tt2015-sz/p/4744181.html
Copyright © 2020-2023  润新知