Microsoft MVP성태의 닷넷 이야기
.NET Framework: 142. WPF - Grid 컨트롤의 ShowGridLine 개선 [링크 복사], [링크+제목 복사],
조회: 30289
글쓴 사람
정성태 (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]

... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12223정성태6/9/202014545.NET Framework: 908. C# - Source Generator 소개 [10]파일 다운로드2
12222정성태6/3/202010362VS.NET IDE: 146. error information: "CryptQueryObject" (-2147024893/0x80070003)
12221정성태6/3/202010115Windows: 170. 비어 있지 않은 디렉터리로 symbolic link(junction) 연결하는 방법
12220정성태6/3/202012633.NET Framework: 907. C# DLL로부터 TLB 및 C/C++ 헤더 파일(TLH)을 생성하는 방법
12219정성태6/1/202011683.NET Framework: 906. C# - lock (this), lock (typeof(...))를 사용하면 안 되는 이유파일 다운로드1
12218정성태5/27/202011663.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법 [3]
12217정성태5/24/202010073오류 유형: 615. Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 0, current count = 1.
12216정성태5/15/202013252.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기 [14]파일 다운로드1
12215정성태5/12/202018363개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링 [10]파일 다운로드1
12214정성태5/5/202010617개발 환경 구성: 489. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 (2) - UEFI/SecureBoot [1]
12213정성태5/3/202012288개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
12212정성태5/1/20209912개발 환경 구성: 487. UEFI / Secure Boot 상태인지 확인하는 방법
12211정성태4/27/202012245개발 환경 구성: 486. WSL에서 Makefile로 공개된 리눅스 환경의 C/C++ 소스 코드 빌드
12210정성태4/20/202012697.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202010726오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202010148Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/20209119스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011445오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208806스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208629스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010711오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013271개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202011106오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011488VS.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/20209310오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202012112오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...