WPF中TypeConverter类的使用

前台xaml代码:

<Window x:Class="HelloWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:HelloWPF"
        Title="MainWindow" Height="350" Width="525" Background="LightBlue">   
    <Window.Resources>   
        <local:Human x:Key="human" Name="Tim" Children="LittleTim"></local:Human>
    </Window.Resources>
    <Grid>     
        <Button Content="click" Height="20" Click="button1_Click" Name="button1" Margin="230,148,228,143" />
    </Grid>
</Window>

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace HelloWPF
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {       
            Human h = this.FindResource("human") as Human;  //在没使用TypeConverter类情况下,前台资源中Children="LittleTim",不能智能从"LittleTim"转换为一个                                                                                                                   //Children,所以会报错
            MessageBox.Show(h.Children.Name);
        }
    }

    [TypeConverterAttribute(typeof(NameToHumanTyperConvert))]
    public class Human
    {
       
        public string Name { get; set; }
        public Human Children { get; set; }
    }

    public class NameToHumanTyperConvert : TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string name = value.ToString();
            Human human = new Human();
            human.Name = name;
            return human;
        }
    }

}

原文地址:https://www.cnblogs.com/tianguook/p/2023021.html