Microsoft MVP성태의 닷넷 이야기
.NET Framework: 103. WPF - ControlTemplate을 코드에서 다뤄보기 [링크 복사], [링크+제목 복사],
조회: 23825
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 



WPF - ControlTemplate을 코드에서 다뤄보기


일반적인 예를 들어서, 아래와 같은 ComboBox의 영역에서 아래로 펼쳐지는 팝업 부분의 바탕색을 바꾸고 싶은데 어떻게 해야 하냐는 것입니다.

wpf_template_customize_1.png

사실, ComboBoxItem 속성의 Background를 잘 안다면 다음과 같이 해결할 수 있습니다.

<ComboBox>
    <ComboBoxItem Background="Blue">test1</ComboBoxItem>
    <ComboBoxItem Background="Blue">test2</ComboBoxItem>
    <ComboBoxItem Background="Blue">test3</ComboBoxItem>
    <ComboBoxItem Background="Blue">test4</ComboBoxItem>
</ComboBox>

그런데, 이번 이야기의 주제는 ControlTemplate을 건드려보는 것이니 ^^ 위와 같은 방법이 아닌 원래의 ComboBox를 구성하고 있는 리소스를 다루는 방법으로 해결해 보겠습니다.

Blend를 사용해 보신 분들은 아시겠지만, ComboBox는 다음과 같은 형식으로 구성되어 있습니다.

<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type ComboBox}">
            <Grid SnapsToDevicePixels="true" x:Name="MainGrid">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition ... Width="0"/>
                
                </Grid.ColumnDefinitions>
                <Popup AllowsTransparency="true" ... x:Name="PART_Popup" Grid.ColumnSpan="2">
                    <Microsoft_Windows_Themes:SystemDropShadowChrome ... Color="Transparent">
                        <Border x:Name="DropDownBorder" ... BorderThickness="1">

                        ...

                        </Border>
                    </Microsoft_Windows_Themes:SystemDropShadowChrome>
                </Popup>
                <ToggleButton ... Grid.ColumnSpan="2"/>
                <ContentPresenter ... "/>
            </Grid>
        </ControlTemplate>
    </Setter.Value>
</Setter>

짐작으로도, ComboBox 항목들이 Popup에 나타난다는 것을 알 수 있고, Popup의 Child로 정의된 Border 요소의 Background를 바꿔주면 쉽게 해결이 될 것 같아 보입니다. 물론, 이를 변경하기 위해서 리소스를 재정의하는 방법을 사용하면 됩니다. 하지만... ^^ 다시 한번 말씀드리자면, 제목에서 밝혔듯이 "코드"에서 접근하는 것을 알고 싶기 때문에 여기서는 그 방법을 사용하지는 않을 것입니다. (사실, 요즘 진행하고 있는 프로젝트에서 리소스가 아닌 코드에서 제어해야 하는 경우가 발생했습니다.)

일단, 코드에서 ControlTemplate을 이용하여 접근하려면 다음과 같이 Template 요소로부터 시작할 수 있습니다.

ControlTemplate ctl = this.comboBox1.Template;

그런데, 아쉽게도 여기서 막힙니다. ControlTemplate은 사실 인스턴스화 되기 이전에 FrameworkElementFactory 등을 이용해서 정의하는 구조이기 때문에 여기에는 Child 요소들에 대한 Instance를 위한 배려가 없습니다. 대신에, FindName을 이용해서 직접 조회하는 방법을 사용해야 합니다.

Border border = ctl.FindName("DropDownBorder", this.comboBox1) as Border;
if (border != null)
{
    border.Background = new SolidColorBrush(Colors.Blue);
}

혹시, 위와 같은 방법보다 더 좋은 접근 방법을 아시는 분은 ^^ 댓글 부탁드리겠습니다.



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







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

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

비밀번호

댓글 작성자
 



2017-01-19 06시59분
[nen] 문제 해결이 안되었는데 이 글 보고 해결했습니다.
[guest]

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12416정성태11/19/202017456오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017571.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019771VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018690.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020808.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017553오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017784디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019613.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034852도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019978.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020933.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018922.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019521.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018305.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019902.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202019204VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015393오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018808.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018491오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018533.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015440VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018333오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015951오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015459오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019984.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019798디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...