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、使用扩展标签的形式

 

转载于:https://www.cnblogs.com/chenyongblog/p/3377971.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值