吴佳鑫的个人专栏

当日事当日毕,没有任何借口

导航

silverlight在XAML资源中实例化CLR对象

可以在资源中创建.net基类库中现有类型(或用户项目中的自定义类型)的对象,当程序运行时会自动实例化它们。

示例:

先创建一个Student类。

public class Student
{
public string Name
{
get;
set;
}
public bool IsFemale
{
get;
set;
}

public override string ToString()
{
if (IsFemale)
return Name + ":女";
else
return Name + ":男";
}

public static string StaticInformation = "我是Student类型所定义的静态字段!";
}

 

在主窗体中,首先引入student类所在的命名空间,并且给其定义了一个 "local:" 前缀;

xmlns:local="clr-namespace:UseCustomizeClass"

 

然后,在资源中创建Student对象并初始化其属性:(以下是WPF的XAML,SL类同)

    <Window.Resources>
<local:Student Name="张三" IsFemale="False" x:Key="student1"/>

</Window.Resources>

现在,即可在窗体中使用此资源了,以下代码使用XAML扩展标记 " x:static" 访问 Student 类的静态字段:

 

    <StackPanel Margin="10">
<Button Margin="10" Click="Button_Click">C#代码访问资源中保存的Student对象属性</Button>
<TextBlock HorizontalAlignment="Center" Text="{x:Static local:Student.StaticInformation}" />
</StackPanel>

 

 

以C#代码获取Student对象的引用,进而可访问它的实例属性:(WPF示例代码,SL类同)

 

        private void Button_Click(object sender, RoutedEventArgs e)
{
Student stu = this.FindResource("student1") as Student;
if (stu != null)
MessageBox.Show(stu.ToString());
}




posted on 2012-01-18 11:02  _eagle  阅读(842)  评论(0编辑  收藏  举报