Fork me on GitHub

XAML系列学习

在XAML中为属性赋值

1、使用Attribute=value形式

<Rectangle Width="100" Height="100" Stroke="Red" Fill="LightGreen" RadiusX="10" RadiusY="10"></Rectangle>

2、使用属性标签的形式

<Window.Resources>
        <local:Animal x:Key="animal" name="Dog" newAnimal="ant"></local:Animal>
</Window.Resources>
        private void Show_Click(object sender, RoutedEventArgs e)
        {
            Animal animal =(Animal)this.FindResource("animal");
            MessageBox.Show(animal.newAnimal.name);
        }

这时提示的是Animal这个类不支持从String进行转换,那么使用TypeConverter类将XAML标签的Attribute与对象的Property进行映射

    [TypeConverterAttribute(typeof(StringToAnimalTypeConverter))]
    public class Animal
    {
        public string name { get; set; }
        public Animal newAnimal { get; set; }
    }

    public class StringToAnimalTypeConverter:TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                Animal animal = new Animal();
                animal.name = value as string;
                return animal;
            }
            return base.ConvertFrom(context, culture, value);
        }
    }

public class StringToAnimalTypeConverter:TypeConverter-------------------using System.ComponentModelTypeConverter

提供一种将值类型转换为其他类型以及访问标准类型的值和属性的统一方法

还需要将[TypeConverterAttribute(typeof(StringToAnimalTypeConverter))] 这个特性添加到类Animal上,表明其类型是可以转换的;[TypeConverter(typeof(StringToAnimalTypeConverter))],之所以加上Attribute是方便好看


 

3、使用扩展标签的形式

 

posted @ 2013-10-19 16:12  种花生的读书人  阅读(164)  评论(0编辑  收藏  举报

该博客仅作为记录笔记,转载随意