标签:
视频地址: XAML中为对象属性赋值的语法
<window />
”表示声明一个窗体对象。 <Button Width="100" Height="30"/>
若属性不是字符串格式,应该怎么办呢?这个时候需要将value转换为属性类型,并赋值给对象。
1、在.cs文件中,我们新建一个Animal类
namespace HelloWPF
{
public class Animal
{
public string name { get; set; }
public Animal animal { get; set; }
}
}
2、在.xaml的命名空间中引用Animal所在的命名空间:
<Window x:Class="HelloWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:HelloWPF"
Title="MainWindow" Height="350" Width="525">
</Window>
3、将Animal对象作为资源声明,并为对象属性赋值
1、在xaml文件中对对象的string类型属性赋值,并在.cs文件中获取值:
<Window.Resources>
<local:Animal x:Key="animal" name="Hello Ketty"></local:Animal>
</Window.Resources>
<Window.Resources>
:以字典的形式维护一系列资源。
Animal cat = this.FindResource("animal") as Animal;
MessageBox.Show(cat.name);
2、在xaml文件中对对象的Animal类型属性赋值,并在.cs文件中获取值:
<Window.Resources>
<local:Animal x:Key="animal" Name="Hello Ketty" animal="Doggy"></local:Animal>
</Window.Resources>
public class Animal
{
public string Name { get; set; }
public Animal animal { get; set; }
}
public class NameToAnimalTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string name = value.ToString();
Animal animal = new Animal();
animal.Name = name;
return animal;
}
}
.cs文件中获取xaml 文件中的Animal对象的animal属性
Animal cat = this.FindResource("animal") as Animal;
if (cat != null)
MessageBox.Show(cat.animal.Name);
标签:
原文地址:http://blog.csdn.net/goon202/article/details/51368058