Microsoft MVP성태의 닷넷 이야기
.NET Framework: 140. WPF - CellPadding 속성을 구현하는 Grid Layout [링크 복사], [링크+제목 복사],
조회: 26300
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

WPF - CellPadding 속성을 구현하는 Grid Layout


HTML Table을 다뤄보신 분들은 WPF의 Grid를 보면서 CellPadding 기능을 아쉬워할 것입니다. 저뿐만 아니라 많은 분들이 공감하고 있는데요.

이에 대한 해결책으로 검색해 봐도 딱히 신통치 않습니다.
그나마 검색되는 사이트가 ... 오호... 뜻밖에도 국내 블로거의 글입니다.

Layout System in WPF : 프롤로그
; http://illef.tistory.com/tag/cellpadding

위의 글을 쓴 "illef" 님은 최근에 상속을 통해서 CellPadding을 구현한 것을 내부 공개를 했는데 ... 저도 다른 식으로 한번 해결해 보고 싶어서 이거저거 뚝딱거려 보았습니다.




우선, 해결을 위한 "생각"은 간단합니다. Grid에 추가되는 1차 자식노드들에 대해서 Margin을 적용하면 그만인 것입니다. 생각이 간단한 만큼, 구현도 간단하게 끝납니다. 왜냐하면, Grid는 이런 경우를 위해 아래와 같은 메서드를 virtual로 제공해 주고 있기 때문입니다. (엄밀히, Panel 수준에서 제공됩니다.)

protected virtual UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent);

CreateUIElementCollection 메서드를 재정의하면 우리가 만든 UIElementCollection을 반환해 줄 수가 있습니다.

protected override UIElementCollection CreateUIElementCollection(
	FrameworkElement logicalParent)
{
    return new MarginUIElementCollection(logicalParent);
}

UIElementCollection 정의를 기억하시는 분들은 이쯤에서 무릎을 탁 치시겠죠. ^^ 아래의 코드를 보시면 대강 이해가 되실 겁니다.

public class MarginUIElementCollection : UIElementCollection
{
    public MarginUIElementCollection(FrameworkElement logicalParent)
        : base(logicalParent,null)
    {
    }

    public override int Add(UIElement element)
    {
        FrameworkElement childElement = element as FrameworkElement;
        childElement.Margin = new Thickness(3.0);
        return base.Add(element);
    }
}

이렇게 해서, Grid의 Children 컬렉션에 유지되는 1차 자식 요소들에 대해서는 단일하게 Margin이 지정이 되어 HTML 테이블의 CellPadding과 동일한 효과가 발생합니다.

아래는 적용된 예를 보여주고 있습니다.

[그림 1: CellPadding == 3]
wpf_grid_cellpadding_1.png

[그림 2: CellPadding == 10]
wpf_grid_cellpadding_2.png

첨부된 파일은 위에서 설명한 기본 동작외에 의존 속성을 함께 정의한 예제입니다.



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/25/2021]

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

비밀번호

댓글 작성자
 



2009-06-08 03시57분
[사이] "오호... 뜻밖에도 국내 블로거의 글입니다." 정책임님은 센스쟁이~
[guest]
2009-06-08 04시46분
^^
kevin25

... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11049정성태9/24/201620940오류 유형: 357. 윈도우 백업 시 오류 - 0x81000037
11048정성태9/24/201621961VC++: 100. 전역 변수 유형별 실행 파일 크기 차이점
11047정성태9/21/201625793기타: 61. algospot.com - 양자화(Quantization) 문제 [2]파일 다운로드1
11046정성태9/15/201627433개발 환경 구성: 298. Windows 10 - bash 실행 시 시작 디렉터리 자동 변경
11045정성태9/15/201620085Windows: 119. Windows 10 - bash 명령어 창을 실행했는데 바로 닫히는 경우
11044정성태9/15/201620344VS.NET IDE: 112. Visual Studio 확장 - 편집 화면 내에서 링크를 누르면 외부 웹 브라우저에서 열기
11043정성태9/15/201621757.NET Framework: 606. .NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법 [1]파일 다운로드1
11042정성태9/14/201619932오류 유형: 356. Unknown custom metadata item kind: 6
11041정성태9/10/201619406.NET Framework: 605. CLR4 보안 - yield 구문 내에서 SecurityCritical 메서드 사용 불가 - 2번째 이야기
11040정성태9/10/201626698.NET Framework: 604. C# Windows Forms - Drag & Drop 예제 코드 [2]파일 다운로드1
11039정성태9/9/201623212오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201625054VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201628291.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201624774개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201620405오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201624430개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201622295오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201621514개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201617754오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201620311VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201627443.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201621523오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201622573.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201623568Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201622276개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201621573오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
... 106  107  108  109  110  111  112  113  114  [115]  116  117  118  119  120  ...