您的位置:首页 > 其它

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

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: