silverlight XAML 리소스에서 CLR 객체 인스턴스화

4613 단어
자원에서 만들 수 있습니다.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 !";
}
 
메인 창에서 먼저 학생 클래스가 있는 이름 공간을 도입하고'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());
}

좋은 웹페이지 즐겨찾기