수색…


XAML에서 개체 읽기

다음 클래스의 구조를 XAML로 작성한 다음 CLR 객체로 읽어야한다고 가정합니다.

namespace CustomXaml
{
    public class Test
    {
        public string Value { get; set; }
        public List<TestChild> Children { get; set; } = new List<TestChild>(); 
    }

    public class TestChild
    {
        public string StringValue { get; set; }
        public int IntValue { get; set; }
    }
}

클래스에는 명시 적 생성자가 없거나 빈 생성자가 있어야합니다. XAML을 깨끗하게 유지하려면 컬렉션을 초기화해야합니다. XAML의 컬렉션 초기화도 가능합니다.

XAML을 읽으려면 XamlServices 클래스를 사용할 수 있습니다. 참조에 추가해야하는 System.Xaml 정의되어 있습니다. 다음 행은 test.xaml 파일을 디스크에서 읽습니다.

Test test = XamlServices.Load("test.xaml") as Test;

XamlServices.Load 메서드에는 스트림 및 기타 소스에서로드 할 여러 오버로드가 있습니다. 포함 된 파일에서 XAML을 읽는 경우 (WPF에서 수행 된 것처럼) 기본적으로 Page 로 설정된 Build Action 속성을 ie Embedded Resource 로 변경해야합니다. 그렇지 않으면 컴파일러에서 WPF 어셈블리에 대한 참조를 요청합니다.

읽을 XAML 파일의 내용은 다음과 같습니다.

<Test xmlns="clr-namespace:CustomXaml;assembly=CustomXaml"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Value="test">
    <Test.Children>
        <TestChild StringValue="abc" IntValue="123"/>
        <TestChild StringValue="{x:Null}" IntValue="456"/>
    </Test.Children>
</Test>

pure xmlns Definition은 접두어없이 동일한 네임 스페이스의 클래스를 사용할 수 있도록합니다. xmlns:x 의 정의는 {x:Null} 과 같은 구문을 사용하는 데 필요합니다. 물론 다른 네임 스페이스 또는 어셈블리의 접두사를 필요에 따라 정의 할 수 있습니다.

XAML에 개체 작성

다음 클래스의 구조를 XAML로 작성한 다음 CLR 객체로 읽어야한다고 가정합니다.

namespace CustomXaml
{
    public class Test
    {
        public string Value { get; set; }
        public List<TestChild> Children { get; set; } = new List<TestChild>(); 
    }
    
    public class TestChild
    {
        public string StringValue { get; set; }
        public int IntValue { get; set; }
    }
}

XAML을 작성하려면 XamlServices 클래스를 사용할 수 있습니다. 참조에 추가해야하는 System.Xaml 정의되어 있습니다. 다음 행은 Test 유형의 인스턴스 test 를 디스크의 test.xaml 파일에 test.xaml .

XamlServices.Save("test.xaml", test);

XamlServices.Save 메서드에는 스트림과 다른 대상에 쓰는 오버로드가 여러 개 있습니다. 결과 XAML은 다음과 같이 보일 것입니다.

<Test Value="test" xmlns="clr-namespace:CustomXaml;assembly=CustomXaml"
                   xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib"
                   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Test.Children>
    <scg:List x:TypeArguments="TestChild" Capacity="4">
      <TestChild IntValue="123" StringValue="abc" />
      <TestChild IntValue="456" StringValue="{x:Null}" />
    </scg:List>
  </Test.Children>
</Test>

pure xmlns Definition은 접두어없이 동일한 네임 스페이스의 클래스를 사용할 수 있도록합니다. xmlns:x 의 정의는 {x:Null} 과 같은 구문을 사용하는 데 필요합니다. 작성자는 Test 객체의 Children 속성에 대해 List<TestChild> 를 초기화하기 위해 xmlns:scg 를 자동으로 추가합니다. 생성자에 의해 초기화되는 속성에 의존하지 않습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow