Microsoft MVP성태의 닷넷 이야기
.NET Framework: 142. WPF - Grid 컨트롤의 ShowGridLine 개선 [링크 복사], [링크+제목 복사],
조회: 30284
글쓴 사람
정성태 (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)
12402정성태11/7/202011845.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202010860VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/20207793오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202011460.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202010005오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202010188.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/20208468VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209816오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208203오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208703오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012807.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011055디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010801.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010248오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011033.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011264Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209094오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010299오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011204.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208918오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010585VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207973오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202011011.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010417.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011713디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208406오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...