深入显出WPF 第一部分(2)

深入浅出WPF 第一部分(2)

3.2 XAML中为对象属性赋值的语法

3.2.1 使用标签的Attribute为对象属性赋值

    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">
        <Rectangle x:Name="rectangle" Width="200" Height="120" Fill="Blue"/>
        <!--SolidColorBush sBrush=new SolidColorBrush();
            sBrush.Color=Colors.Blue;
            this.rectangle.Fill=sBrush;
        -->
    </Grid>

3.2.2 使用TypeConverter类将XAML标签的Attribute与对象的Property进行映射。

//Human.cs
using System.ComponentModel;

namespace FirstWpfApplication
{
    [TypeConverter(typeof(StringToHumanTypeConverter))]
    public class Human
    {
        public string Name { get; set; }
        public Human Child { get; set; }
    }
}

//StringToHumanTypeConverter.cs
using System.ComponentModel;

namespace FirstWpfApplication
{
    class StringToHumanTypeConverter : TypeConverter
    {
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
            {
                Human h = new Human() { Name = value as string };
                return h;
            }
            return base.ConvertFrom(context, culture, value);
        }
    }
}
<Window x:Class="FirstWpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:FirstWpfApplication" 
        Title="Anders" Height="173" Width="296">
    <!--xmlns:local定义-->
    <Grid >
        <Button Name="button1" Click="button1_Click" Margin="5"/>
    </Grid>
    <Window.Resources>
        <local:Human x:Key="human" Child="Anders.F" Name="Anders.H" />
    </Window.Resources>
</Window>

using System.Windows;

namespace FirstWpfApplication
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public string Str { get; set; }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Human h = this.FindResource("human") as Human;
            MessageBox.Show(string.Format("Name:{0} ChildName:{1}", h.Name, h.Child.Name));
        }
    }
}