• 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;
            }
        }

    }

  • 相关阅读:
    关于打开MTK_SDCARD_SWAP 宏后MTK目前升级方案和 关于打开MTK_SHARED_SDCARD宏后MTK目前升级方案
    报表填报时,如何实现多个单元格绑定一个字段?
    双4G LTE
    报表移动端如何进行移动设备绑定与撤销
    各种卡的一些信息积累
    广佛肇城轨年内通车 佛山西站预计2017年中通车
    Web报表页面如何传递中文参数
    根据条件控制参数控件是否显示(可用)
    如何对报表的参数控件赋值
    Jquery前端分页插件pagination同步加载和异步加载
  • 原文地址:https://www.cnblogs.com/tianguook/p/2023021.html
Copyright © 2020-2023  润新知