Xmal中引用自定义的类、类型转换继承TypeConvert
2017-02-28 15:54
323 查看
一、XAML引用类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel; //加上这个空间
1、定义类
namespace 第一个WPF
{
[TypeConverter(typeof(Converter))]
类型转换,必须有
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
}
}
2、xaml中引用
xmlns:Human="clr-namespace:第一个WPF",[b]clr-namespace必须有[/b]
[b]3、创建Window.Resources段[/b]
<Window.Resources>
<Human:Human x:Key="123" Child="asd"/>
</Window.Resources>
[b]二、类型转换[/b]
从TypeConverter中派生出自己的类,并重写它的一个ConvertFrom方法。这个方法有一个参数名为value,我们要做的就是讲这个值“翻译”成合适的值赋给对象的属性。类似于int.TryParse
class
Converter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Human h = (Human)this.FindResource("123");
MessageBox.Show(h.Child.Name); //human.Child是human类型,而在xaml代码中“asd”是字符串,编译器不知道如何把“asd”字符串转换为
//Human实例,所以必须实现TypeConvert
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel; //加上这个空间
1、定义类
namespace 第一个WPF
{
[TypeConverter(typeof(Converter))]
类型转换,必须有
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
}
}
2、xaml中引用
xmlns:Human="clr-namespace:第一个WPF",[b]clr-namespace必须有[/b]
[b]3、创建Window.Resources段[/b]
<Window.Resources>
<Human:Human x:Key="123" Child="asd"/>
</Window.Resources>
[b]二、类型转换[/b]
从TypeConverter中派生出自己的类,并重写它的一个ConvertFrom方法。这个方法有一个参数名为value,我们要做的就是讲这个值“翻译”成合适的值赋给对象的属性。类似于int.TryParse
class
Converter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Human h = (Human)this.FindResource("123");
MessageBox.Show(h.Child.Name); //human.Child是human类型,而在xaml代码中“asd”是字符串,编译器不知道如何把“asd”字符串转换为
//Human实例,所以必须实现TypeConvert
}
相关文章推荐
- 重载操作符operator()与用户自定义类型转换
- 深入Atlas系列:Web Sevices Access in Atlas示例(5) - 自定义TypeConverter把基础类型转换为复杂类型
- 【引用】C中的类型转换
- 让自定义的类型可以和任意的类型之间转换
- Castle的自定义类型转换
- 让自定义的类型可以和任意的类型之间转换
- 让自定义的类型可以和任意的类型之间转换
- 让自定义的类型可以和任意的类型之间转换
- 自定义显式类型转换 --explicit
- DirectCast 介绍基于继承或实现的类型转换操作。
- 引用COM组件时“将类型库转换为.NET程序集失败”的解决办法
- 引用与类型转换的区别
- 让自定义的类型可以和任意的类型之间转换
- ASP.Net中用ViewState存储自定义复杂对象后类型转换的一个问题
- 十二章 类————初始化const或引用类型要用初始化列表,隐式转换问题等,友元
- ---类型描述 ---值类型 ---引用类型 ---类型之间的转换 ---装箱和拆箱
- 关于C++和C#的自定义数据类型转换的一些思考
- 让自定义的类型可以和任意的类型之间转换
- Castle的自定义类型转换
- 接口继承的值类型和引用类型