Microsoft MVP성태의 닷넷 이야기
.NET Framework: 142. WPF - Grid 컨트롤의 ShowGridLine 개선 [링크 복사], [링크+제목 복사],
조회: 37366
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

WPF - Grid 컨트롤의 ShowGridLine 개선


지난번에는 HTML 테이블의 Cell Padding에 해당하는 기능을 구현해 보았는데요.

WPF - CellPadding 속성을 구현하는 Grid Layout
; https://www.sysnet.pe.kr/2/0/734

역시나, HTML Table 태그를 사용해보신 분들은 또 한 가지 아쉬운 기능이 있을 것입니다. 바로 Cell 간의 Border 속성이 그것인데요.

예를 들어, 다음과 같은 HTML Table의 경우,

<table style="width: 300px; height: 300px;" border="1">
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td rowspan=2>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td colspan=2>&nbsp;</td>
    </tr>
</table>

아래와 같은 식으로 나오게 됩니다.

[그림 1: Border가 지정된 HTML Table]
wpf_grid_show_grid_line_1.png

이제 WPF에서 제공되는 Grid Panel과 비교해 볼까요?
다행히, WPF Grid 역시 Border와 비슷한 기능을 제공합니다. "ShowGridLines" 의존 속성을 지원하는데, 이를 지정하면 다음과 같은 식으로 보이게 됩니다.

[그림 2: ShowGridLines="True"가 지정된 Grid]
wpf_grid_show_grid_line_2.png

불행히도, 보시는 것처럼 ShowGridLines 속성이 왜 있을까 하는 의문이 들 정도입니다. 사실, Microsoft에서는 이 기능을 사용하지 말라고 권고하고 있습니다.

.NET Framework Class Library - Grid.ShowGridLines Property
; https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.grid.showgridlines#System_Windows_Controls_Grid_ShowGridLines

Only dotted lines are available because this property is intended as a design tool to debug layout problems and is not intended for use in production quality code. If you want lines inside a Grid, style the elements within the Grid to have borders.



스타일로 해결하라는데, ... 그건 디자인 잘 하시는 분들이 해결해 주시고. ^^ 저는 프로그래밍으로 접근해 보겠습니다.

일단, 검색을 해보죠.

How can I change the color of the gridlines of a Grid in WPF?
; http://stackoverflow.com/questions/606220/how-can-i-change-the-color-of-the-gridlines-of-a-grid-in-wpf

위의 글은 원인은 분석하였으나 답을 내주지 못했습니다. 그래서 좀 더 ^^ 찾아보면,

WPF Grid Question
; http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/74e36c60-b93a-47c7-8214-79669ec6b121/

오... 그나마 괜찮은 대답입니다.

코드는 그저 Grid에 OnRender 부분만 다음과 같이 재정의해주면 됩니다.

public class CustomGrid : Grid  
{  
    Pen line = new Pen(Brushes.Black, 1);  
    protected override void OnRender(System.Windows.Media.DrawingContext dc)  
    {  
        base.OnRender(dc);  
        dc.DrawRectangle(null, line, new Rect(0,0,this.ActualWidth, this.ActualHeight));  
        double height = 0;  
        foreach (var r in this.RowDefinitions)  
        {  
            height += r.ActualHeight;  
            dc.DrawLine(line, new Point(0, height), new Point(this.ActualWidth,height));  
        }  
        double width = 0;  
        foreach (var c in this.ColumnDefinitions)  
        {  
            width += c.ActualWidth;  
            dc.DrawLine(line, new Point(width, this.ActualHeight), new Point(width, 0));  
        }  
    }  
}  

와~~~ 간단하지요. ^^ 그런데, 정작 적용해 보면 다양한 상황을 고려하지 않았음을 알 수 있습니다. 예를 들어, 아래의 그림과 같이 나옵니다.

[그림 3: RowSpan/ColumnSpan이 고려되지 않은 Cell Border]
wpf_grid_show_grid_line_3.png

그럼, 이 부분을 다듬으면 문제는 해결이 되는데요. 생각 자체는 그리 어렵지 않습니다. 예를 들어, 가로선을 그을 때(Row별로) 칼럼 단위만큼 그리며 진행하다가 다음번 그려야 될 곳이 RowSpan으로 되어 있으면 그 구획은 긋지 말고 건너뛰면 됩니다. 세로선도 마찬가지겠지요.

그렇게 생각한 데로 구현해서 보정하면, 최종적으로 아래와 같이 나옵니다. 이 정도면... 괜찮지 않나요! ^^

[그림 4: RowSpan/ColumnSpan 영역을 고려한 Cell Border]
wpf_grid_show_grid_line_4.png

보정된 소스 코드는 첨부된 솔루션 압축 파일에 있습니다. (2023-04-20: 덧글의 Lyn 님의 소스코드가 반영됐습니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/20/2023]

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

비밀번호

댓글 작성자
 



2017-08-27 06시16분
[Lyn] 안녕하세요. 해당 코드 잘 참고 하여 감사의 인사를 드립니다. 제가 사용하기 위해 수정 한 코드를 https://lunapiece.net/Article/14007914 에 올려놓았습니다
[guest]
2017-08-28 08시34분
[정환나라] 성태님 혹시나 해서 말씀드리는데 코드같은것들을 첨부하지마시고 Github에 공개해서 진행하시는건 어떨지 여쭤봅니다.
[guest]
2017-08-28 09시23분
@Lyn 글 잘봤습니다. ^^ 그러고 보니, 벌써 8년 가량이 흘렀군요.

@정환나라 이게 워낙 별다르게 큰 묶음이 아니라서... ^^; 일일이 올리는 것도 참 애매합니다. repo 생성도 그렇고.
정성태
2021-03-11 08시50분
[Wow User] 덕분에 좋은 오픈소스 받아갑니다. 감사합니다.
[guest]
2021-06-13 04시08분
[Lyn] 블로그가 옮겨져서 혹시 찾으시는분 계실까봐 링크 옮겨 달아둡니다

http://blog.lunapiece.net/posts/WPF-Border-Grid/
[guest]

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12211정성태4/27/202019264개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202020708.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202017414오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202015977Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015828스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018445오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015105스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015105스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017951오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021208개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018438오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018530VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016172오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019532오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018829VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015949오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018268.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020999오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017916개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019939개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021048개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015628오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021231개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026023Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015598오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017402오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...