zoukankan      html  css  js  c++  java
  • 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;
            }
        }

    }

  • 相关阅读:
    简历的快速复制
    使用stringstream对象简化类型转换
    猴子吃桃
    new和delete运算符
    绘制正余弦曲线
    计算学生的平均成绩
    判断是否为回文字符串
    统计各种字符个数
    验证用户名
    回溯法(挑战编程)
  • 原文地址:https://www.cnblogs.com/tianguook/p/2023021.html
Copyright © 2011-2022 走看看