Microsoft MVP성태의 닷넷 이야기
.NET Framework: 150. WPF - Property Element 사용 의미 [링크 복사], [링크+제목 복사],
조회: 27939
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일


Property Element 사용 의미


혹시 "Property Element"에 대해 잘 모르시는 분들을 위해 잠시 설명하자면.

보통, 요소의 속성값에 대해서 다음과 같은 식으로 설정하죠.

<TextBox Text="test">
</TextBox>

그런데, 아래와 같이 복잡(?)하게 정의하는 것도 가능합니다.

<TextBox>
    <TextBox.Text>
    test
    </TextBox.Text>
</TextBox>

바로 위와 같이 속성(Property)을 별도로 분리해 내어 하위 Element로 정의하는 것을 "Property Element"라고 부릅니다.

저같은 경우, 처음 페졸드의 책에서 "Property Element"를 보면서, "흠... 뭐 저렇게 복잡하게 사용할 일이 있겠어?"라는 식으로 무시하고 지나갔었습니다. 역시나~~~ 괜히 써 놓은 글이 아니라는 것을 깨닫기에 그리 긴 시간이 걸리지는 않더군요. ^^




Property가 Complex Type인 경우에는 "Property Element" 식으로 정의를 해야하는 경우가 종종 있습니다. 이전에 소개해 드린 아래와 같은 사례가 그 좋은 예이지요.

ConveterParameter로 1개 이상의 값을 전달하고 싶다면? 
; http://blogs.msdn.com/permanenttan/archive/2009/06/19/array-as-a-wpf-converterparameter.aspx

이외에도 XAML상에서 컴파일 오류가 발생하는 경우가 종종 있는데, 바로 그런 경우에도 "Property Element" 방식을 사용하면 컴파일 오류를 피할 수 있습니다.

예를 한번 들어볼까요?

"illef" 님의 블로그에서 소개된 "Converter Manager"를 보면,

Converter Manager
; http://illef.tistory.com/entry/Converter-Manager

아래와 같은 내용이 나옵니다.

공통된 Library로 Assembly를 별도로 관리한 다는 의미도 있지만 또 다른 이유는 Microsoft 팀의 버그 때문입니다. 같은 Assembly안에 있으면 MarkUpExtension을 XAML의 Attribute로 설정할 수 없는 버그입니다. (ㅡ.ㅡ)



아쉽게도 illef 님의 글에서 에러 내용은 공개되지 않았지만 아마도 아래와 같은 식일 것으로 추정됩니다.

Unknown property ‘Converter’ for type ‘MS.Internal.Markup.MarkupExtensionParser+UnknownMarkupExtension’ encountered while parsing a Markup Extension.

하나의 프로젝트에서 빌드했는데도 위와 같은 에러가 없는 경우도 있습니다. 저같은 경우에는 다음과 같이 디자이너 화면에서 경고가 발생했습니다.

[그림 1: 디자이너에서 오류 발생]
property_element_usecase_1.png
"No constructor for type 'StaticConverterExtension' has 1 parameters"


다행히 빌드는 되지만, 어쩐지 저런 톱니 모양 밑줄이 그어지는 것이 꺼림직한데요. 바로 이런 경우에 "Property Element"를 사용하면 위와 같은 경고를 피할 수 있습니다.

<Button.Content>
    <Binding Path="ButtonTitle">
        <Binding.Converter>
            <local:StaticConverterExtension Type="{x:Type local:IntToBooleanConverter}" />
        </Binding.Converter>
    </Binding>
</Button.Content>

*** 위의 과정을 테스트한 프로젝트를 첨부해놓았으니 참고하십시오.




이와 관련한 지식을, 이번에 Sibling MarkupExtension을 구현하면서 보게 된 아래의 글에서 알게 되었습니다.

A base class for custom WPF binding markup extensions
; http://www.hardcodet.net/2008/04/wpf-custom-binding-class

위의 내용에서 "Problem: Attribute syntax with resources" 부분을 보면, 아래와 같이 XAML을 사용했는데 컴파일 오류가 발생한다고 합니다.

<TextBox Name="txtZipCode"
         Text="{local:LookupExtension Source={StaticResource MyAddress}
                                      Path=ZipCode,
                                      LookupKey=F5}"
/>

그런데, 아래와 같이 "Property Element" 구문으로 사용하면 오류가 안 난다고 하지요.

<TextBox Name="txtZipCode">
  <TextBox.Text>
    <local:LookupExtension Source="{StaticResource MyAddress}"
                           Path="ZipCode"
                           LookupKey="F5" />
  </TextBox.Text>
</TextBox>

그러면서, 그와 관련된 내용을 정리한 다음의 글을 소개하고 있습니다.

Custom MarkupExtension && Nested Extensions == Bug
; http://www.hardcodet.net/2008/04/nested-markup-extension-bug

다시, 위의 글에서는 2006년 10월에 씌여진 또 다른 글을 소개해 줍니다.

How should I data bind a Polygon’s Points to a data source? - Part II
; http://www.beacosta.com/blog/?p=36

버그라고는 하지만, 2006년도에 알려진 것이라면 아마도 쉽게 수정되지 않는 문제로 보입니다.




여기서 재미있는 점이 하나 있습니다. ^^ "Property Element"로 이렇게 빌드 오류를 수정할 수 있다고 나오는데요.

이것을 다시 처음에 "illef" 님이 지적한 해결방법으로 보면, 해석을 못하는 그 구문과 엮인 요소를 별도의 DLL로 분리해서 참조하면 역시 "Property Element" 방식으로 정의하지 않아도 정상적으로 빌드가 됩니다. 예를 들어, 위에서 소개한 "A base class for custom WPF binding markup extensions" 글의 LookupExtension을 별도의 DLL로 분리하면 다음과 같이 Text 속성에 사용해도 빌드 오류가 발생하지 않습니다.

<TextBox Name="txtCityCustom"
     Height="23"
     HorizontalAlignment="Left"
     Margin="109,246,0,0"
     VerticalAlignment="Top"
     Width="160"
     Text="{external:LookupExtension LookupKey=F6,
                       Path=City,
                       UpdateSourceTrigger=PropertyChanged,
                       Mode=TwoWay,
                       Converter={StaticResource charConv},
                       ConverterParameter=*}">
    
</TextBox>

*** 테스트 된 솔루션 파일을 첨부해 놓았으니 참고하십시오.

정리해 보면,

XAML 컴파일 시에 오류가 나는 "올바른 구문"이 있다면 다음과 같은 2가지 방법을 통해서 해결이 가능합니다.

  1. Property Element 구문을 사용
  2. 별도의 DLL로 분리해서 사용



[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 4/10/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11035정성태8/29/201621665오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201625731개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201623596오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201622809개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201618915오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201622102VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201629367.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201622365오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201624076.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201625280Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201624110개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201623325오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201624895개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201625378개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201622242오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201625286VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201642116기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201626288.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201627634웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201625607개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201623911오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201624665오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
11013정성태8/6/201635514개발 환경 구성: 290. Windows 10에서 경험해 보는 Windows Containers와 docker [4]
11012정성태8/6/201625567오류 유형: 346. Windows 10에서 Windows Containers의 docker run 실행 시 encountered an error during CreateContainer failed in Win32 발생
11011정성태8/6/201627088기타: 59. outlook.live.com 메일 서비스의 아웃룩 POP3 설정하는 방법
11010정성태8/6/201624066기타: 58. Outlook에 설정한 SMTP/POP3(예:천리안 메일) 계정 암호를 잊어버린 경우
... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...