一:在xaml中代码:红色部分为自己添加的
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <local:Human x:Key="human" Name="tim" Child="little"/> </Window.Resources> <Grid> <Button Content="Button" Height="30" HorizontalAlignment="Left" Margin="170,107,0,0" Name="button1" VerticalAlignment="Top" Width="142" Click="button1_Click" /> </Grid> </Window>
在cs中的代码:
namespace WpfApplication1 { /// <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; if (h != null) { MessageBox.Show(h.Child.Name); } } } [TypeConverterAttribute(typeof(NameToHumanTypeConverter))] public class Human { public string Name { 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 child = new Human(); child.Name = name; return child; } } }
运行的结果,点击按钮:出现little