none
wpf里面typeconverter问题。。。。 RRS feed

  • 问题

  • 后台代码

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    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;
    
    namespace e_plant_software
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                Human h = this.FindResource("human") as Human;
                if (h != null)
                {
                   // MessageBox.Show(h.Name);
                    MessageBox.Show(h.Child.Name);
                }
            }
        }
    
       [TypeConverterAttribute(typeof(NameToHumanTypeConverter))]
        public class Human
        {
            public string Name { get; set; }
    
            public string Age { get; set; }
    
            public Human Child { get; set; }
        }
    
        public class NameToHumanTypeConverter :TypeConverter 
        {
            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            {
                string name = value.ToString();
                Human chlid = new Human();
                chlid.Name = name;
                return chlid;
                //return base.ConvertFrom(context, culture, value);
            }
        }
    }
    

    XAML代码:

    <Window x:Class="e_plant_software.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:e_plant_software"
            Title="MainWindow" Height="350" Width="525" WindowStyle="None">
        <Window.Resources>
            <local:Human x:Key="human" Child="LittleTim" Name="Tim"/>
        </Window.Resources>
        <Grid>
            <Button Content="Show" Click="Button_Click_1" Width="100" Height="50"/>
        </Grid>
    </Window>

    程序能正确运行,但是在VS2012中,设计视图中无法预览设计图,提示Child="LittleTim" 处代码有问题---错误 1 “Human”的 TypeConverter 不支持从字符串进行转换。 

    纠结啊。。

    2012年10月16日 4:12

答案