다음을 통해 공유


연습: 표준 형식의 컬렉션 직렬화

경우에 따라 사용자 지정 컨트롤은 컬렉션을 속성으로 노출합니다. 이 연습에서는 디자인 타임에 컬렉션을 직렬화하는 방법을 제어하는 데 DesignerSerializationVisibilityAttribute 클래스를 사용하는 방법을 보여 줍니다. Content 값을 컬렉션 속성에 적용하면 속성이 직렬화됩니다.

주의

이 콘텐츠는 .NET Framework용으로 작성되었습니다. .NET 6 이상 버전을 사용하는 경우 주의해서 이 콘텐츠를 사용합니다. Windows Forms용 디자이너 시스템이 변경되었으며, .NET Framework 이후 디자이너 변경 내용 문서를 검토하는 것이 중요합니다.

이 항목의 코드를 단일 목록으로 복사하려면 방법: DesignerSerializationVisibilityAttribute를 사용하여 표준 형식의 컬렉션 직렬화를 참조하세요.

사전 요구 사항

이 연습을 완료하려면 Visual Studio가 필요합니다.

직렬화 가능 컬렉션을 사용하여 컨트롤 만들기

첫 번째 단계는 직렬화 가능 컬렉션을 속성으로 포함하는 컨트롤을 만드는 것입니다. 속성 창에서 액세스할 수 있는 컬렉션 편집기를 사용하여 이 컬렉션의 콘텐츠를 편집할 수 있습니다.

  1. Visual Studio에서 Windows 컨트롤 라이브러리 프로젝트를 만들고 이름을 SerializationDemoControlLib로 지정합니다.

  2. UserControl1의 이름을 SerializationDemoControl으로 바꿉니다. 자세한 내용은 코드 기호 이름 바꾸기 리팩터링을 참조하세요.

  3. 속성 창에서 Padding.All 속성의 값을 10으로 설정합니다.

  4. TextBox 컨트롤을 SerializationDemoControl에 배치합니다.

  5. TextBox 컨트롤을 선택합니다. 속성 창에서 다음 속성을 설정합니다.

    속성 다음으로 변경
    여러 줄 true
    Dock Fill
    ScrollBars Vertical
    읽기 전용 true
  6. 코드 편집기에서 SerializationDemoControlstringsValue라는 문자열 배열 필드를 선언합니다.

        // This field backs the Strings property.
    private:
        array<String^>^ stringsValue;
    
    
    
    // This field backs the Strings property.
    private String[] stringsValue = new String[1];
    
    ' This field backs the Strings property.
     Private stringsValue(1) As String
    
  7. SerializationDemoControl에서 Strings 속성을 정의합니다.

    참고

    Content 값은 컬렉션의 serialization을 사용하도록 설정하는 데 사용됩니다.

        // When the DesignerSerializationVisibility attribute has
        // a value of "Content" or "Visible" the designer will 
        // serialize the property. This property can also be edited 
        // at design time with a CollectionEditor.
    public:
        [DesignerSerializationVisibility(
            DesignerSerializationVisibility::Content)]
        property array<String^>^ Strings
        {
            array<String^>^ get()
            {
                return this->stringsValue;
            }
            void set(array<String^>^ value)
            {
                this->stringsValue = value;
    
                // Populate the contained TextBox with the values
                // in the stringsValue array.
                StringBuilder^ sb =
                    gcnew StringBuilder(this->stringsValue->Length);
    
                for (int i = 0; i < this->stringsValue->Length; i++)
                {
                    sb->Append(this->stringsValue[i]);
                    sb->Append(Environment::NewLine);
                }
    
                this->demoControlTextBox->Text = sb->ToString();
            }
        }
    
    // When the DesignerSerializationVisibility attribute has
    // a value of "Content" or "Visible" the designer will
    // serialize the property. This property can also be edited
    // at design time with a CollectionEditor.
    [DesignerSerializationVisibility(
        DesignerSerializationVisibility.Content )]
    public String[] Strings
    {
        get
        {
            return this.stringsValue;
        }
        set
        {
            this.stringsValue = value;
    
            // Populate the contained TextBox with the values
            // in the stringsValue array.
            StringBuilder sb =
                new StringBuilder(this.stringsValue.Length);
    
            for (int i = 0; i < this.stringsValue.Length; i++)
            {
                sb.Append(this.stringsValue[i]);
                sb.Append("\r\n");
            }
    
            this.textBox1.Text = sb.ToString();
        }
    }
    
    ' When the DesignerSerializationVisibility attribute has
    ' a value of "Content" or "Visible" the designer will 
    ' serialize the property. This property can also be edited 
    ' at design time with a CollectionEditor.
     <DesignerSerializationVisibility( _
         DesignerSerializationVisibility.Content)> _
     Public Property Strings() As String()
         Get
             Return Me.stringsValue
         End Get
         Set(ByVal value As String())
             Me.stringsValue = Value
    
             ' Populate the contained TextBox with the values
             ' in the stringsValue array.
             Dim sb As New StringBuilder(Me.stringsValue.Length)
    
             Dim i As Integer
             For i = 0 To (Me.stringsValue.Length) - 1
                 sb.Append(Me.stringsValue(i))
                 sb.Append(ControlChars.Cr + ControlChars.Lf)
             Next i
    
             Me.textBox1.Text = sb.ToString()
         End Set
     End Property
    
  8. F5 키를 눌러 프로젝트를 빌드하고 UserControl 테스트 컨테이너에서 컨트롤을 실행합니다.

  9. UserControl 테스트 컨테이너PropertyGrid에서 Strings 속성을 찾습니다. Strings 속성을 선택한 다음, 줄임표(Visual Studio 속성 창의 줄임표 단추(...)) 단추를 선택하여 문자열 컬렉션 편집기를 엽니다.

  10. 문자열 컬렉션 편집기에서 여러 문자열을 입력합니다. 각 문자열의 끝에 있는 Enter 키를 눌러 문자열을 구분합니다. 문자열 입력이 완료되면 확인을 클릭합니다.

참고

입력한 문자열이 SerializationDemoControlTextBox에 표시됩니다.

컬렉션 속성 직렬화

컨트롤의 serialization 동작을 테스트하려면 컨트롤을 양식에 배치하고 컬렉션 편집기를 사용하여 컬렉션의 콘텐츠를 변경합니다. Windows Forms 디자이너에서 코드를 내보내는 특수 디자이너 파일을 확인하여 직렬화된 컬렉션 상태를 볼 수 있습니다.

  1. Windows 애플리케이션 프로젝트를 솔루션에 추가합니다. 프로젝트 이름을 SerializationDemoControlTest로 지정합니다.

  2. 도구 상자에서 SerializationDemoControlLib 구성 요소라는 탭을 찾습니다. 이 탭에서 SerializationDemoControl을 찾습니다. 자세한 내용은 연습: 도구 상자에 자동으로 사용자 지정 구성 요소 채우기를 참조하세요.

  3. SerializationDemoControl을 양식에 배치합니다.

  4. Strings속성 창에서 속성을 찾습니다. Strings 속성을 클릭한 다음, 줄임표(Visual Studio 속성 창의 줄임표 단추(...)) 단추를 클릭하여 문자열 컬렉션 편집기를 엽니다.

  5. 문자열 컬렉션 편집기에서 여러 문자열을 입력합니다. 각 문자열의 끝에 있는 Enter 키를 눌러 문자열을 구분합니다. 문자열 입력이 완료되면 확인을 클릭합니다.

    참고

    입력한 문자열이 SerializationDemoControlTextBox에 표시됩니다.

  6. 솔루션 탐색기에서 모든 파일 표시 단추를 클릭합니다.

  7. Form1 노드를 엽니다. 바로 아래에 Form1.Designer.cs 또는 Form1.Designer.vb라는 파일이 있습니다. Windows Forms 디자이너가 양식의 디자인 타임 상태와 해당 자식 컨트롤을 나타내는 코드를 이 파일로 내보냅니다. 코드 편집기에서 이 파일을 엽니다.

  8. Windows Form 디자이너 생성 코드라는 지역을 열고 serializationDemoControl1이라는 섹션을 찾습니다. 이 레이블 바로 아래에는 컨트롤의 직렬화된 상태를 나타내는 코드가 있습니다. 5단계에서 입력한 문자열은 Strings 속성에 대한 할당에 표시됩니다. C# 및 Visual Basic의 다음 코드 예제에서는 문자열 “red”, “orange”, “yellow”를 입력한 경우 표시되는 것과 유사한 코드를 보여 줍니다.

    this.serializationDemoControl1.Strings = new string[] {
            "red",
            "orange",
            "yellow"};
    
    Me.serializationDemoControl1.Strings = New String() {"red", "orange", "yellow"}
    
  9. 코드 편집기에서 Strings 속성의 DesignerSerializationVisibilityAttribute 값을 Hidden으로 변경합니다.

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    
  10. 솔루션을 다시 빌드하고 3단계와 4단계를 반복합니다.

참고

이 경우 Windows Forms 디자이너Strings 속성에 대한 할당을 내보내지 않습니다.

다음 단계

표준 형식의 컬렉션을 직렬화하는 방법을 알고 나면 사용자 지정 컨트롤을 디자인 타임 환경에 더 깊게 통합하는 것이 좋습니다. 다음 항목에서는 사용자 지정 컨트롤의 디자인 타임 통합을 개선하는 방법을 설명합니다.

참고 항목