WPF 简单 TypeConvert 测试
XMAL:
<Window x:Class="WpfApp3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp3"
mc:Ignorable="d" WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="500">
<Window.Resources>
<local:Human x:Key="human" Child="Tom"/>
</Window.Resources>
<Grid>
<Button x:Name="btn_HumanTest" Click="btn_HumanTest_Click" Content="Human 测试" Height="40" Width="100" />
</Grid>
</Window>
behind code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
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 WpfApp3
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btn_HumanTest_Click(object sender, RoutedEventArgs e)
{
Human h = FindResource("human") as Human;
MessageBox.Show(h.Child.Name);
}
}
public class StringToHumanTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}
[TypeConverter(typeof(StringToHumanTypeConverter))]
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
}
} // namespace
运行:

来自:《深入浅出 WPF》P21
浙公网安备 33010602011771号