标签:des style blog http io ar color os 使用
XAML中的Attribute只接受String类型的值,例如:
<Grid Background="Red"/>
class Human{private string name;private Human child;public string Name{get { return name; }set { name = value; }}public Human Child{get { return child; }set { child = value; }}public Human(){Name = string.Empty;Child = null;}public Human(string name):this (){Name = name;}}
public class NameToHumanTypeConverter : TypeConverter{public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType){if (sourceType == typeof(string))return true;elsereturn base.CanConvertFrom(context, sourceType);}public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value){if (value != null && value is string){Human human = new Human();human.Name = (string)value;return human;}else{return base.ConvertFrom(context, culture, value);}}}
[TypeConverter(typeof(NameToHumanTypeConverter))]class Human{// ...}
<Window x:Class="类型转换01.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:codes="clr-namespace:类型转换01"Title="MainWindow" Height="350" Width="525"><Window.Resources><codes:Human x:Key="man" Name="Louis" Child="Liu"></codes:Human></Window.Resources><Grid><Button Click="Button_Click"></Button></Grid></Window>
private void Button_Click(object sender, RoutedEventArgs e){Human human = this.FindResource("man") as Human;MessageBox.Show(string.Format("Man: {0}\nChild: {1}", human.Name, human.Child.Name));}

static void Main(string[] args){CoordinateToStringTypeConverter converter = new CoordinateToStringTypeConverter();Coordinate testCoordinate = new Coordinate(1.2, 3.4);string resultString = (string)converter.ConvertFrom(testCoordinate);Console.WriteLine(resultString);resultString = (string)TypeDescriptor.GetConverter(typeof(Coordinate)).ConvertFrom(testCoordinate);Console.WriteLine(resultString);string testString = "5.6,7.8";Coordinate resultCoordinate = (Coordinate)converter.ConvertTo(testString, typeof(Coordinate));Console.WriteLine(resultCoordinate);resultCoordinate = (Coordinate)TypeDescriptor.GetConverter(typeof(Coordinate)).ConvertTo(testString, typeof(Coordinate));Console.WriteLine(resultCoordinate);}
标签:des style blog http io ar color os 使用
原文地址:http://www.cnblogs.com/liuzeyuzh/p/4150131.html