深入浅出WPF笔记

深入浅出WPF

  • 实例演示: 使用类型转换器XAML中将字符串转换为自定义对象
// Human.cs
[TypeConverter(typeof(StringToHumanTypeConverter))] // 指定了自定义的类型转换器
public class Human
{
    public string Name { get; set; }
    public Human Child { get; set; }
}

public class StringToHumanTypeConverter : TypeConverter
{
	// 重写 ConvertFrom 方法,将字符串转换为 Human 对象
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
    	// 当输入是字符串时,创建新的 Human 对象并设置其 Name 属性
        if (value is string)
        {
            Human h = new Human();
            h.Name = value as string;
            return h;
        }
        return base.ConvertFrom(context, culture, value);
    }
}

// xaml
<Window x:Class="WpfApp1.MainWindow"
       ......
        Title="MainWindow" Height="450" Width="800">

    <Window.Resources>
    	<!--在资源中定义了一个 Human 对象-->
		<!--设置 Child="ABC" - 这里会触发类型转换器,将字符串 "ABC" 转换为 Human 对象-->
        <local:Human x:Key="human" Child="ABC" />
    </Window.Resources>
    
    <Grid>
    	<!--绑定点击事件-->
        <Button x:Name="Button1" Click="Button1_Click" Content="测试" />
    </Grid>
</Window>

// 主程序
......
private void Button1_Click(object sender, RoutedEventArgs e)
{
    Human h = (Human)this.FindResource("human"); // 从资源中获取 human 对象
    MessageBox.Show(h.Child.Name); // 显示其 Child 的 Name 属性(即 "ABC")
}


posted @ 2025-11-24 17:12  清安宁  阅读(17)  评论(0)    收藏  举报