Microsoft MVP성태의 닷넷 이야기
.NET Framework: 142. WPF - Grid 컨트롤의 ShowGridLine 개선 [링크 복사], [링크+제목 복사],
조회: 37330
글쓴 사람
정성태 (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)
12689정성태6/25/202118345오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
12688정성태6/24/202117662.NET Framework: 1073. C# - JSON 역/직렬화 시 리플렉션 손실을 없애는 JsonSrcGen [2]파일 다운로드1
12687정성태6/22/202114985오류 유형: 729. Invalid data: Invalid artifact, java se app service only supports .jar artifact
12686정성태6/21/202116947Java: 22. Azure - 자바(Java)로 만드는 Web App Service - Java SE (Embedded Web Server) 호스팅
12685정성태6/21/202118165Java: 21. Azure Web App Service에 배포된 Java 프로세스의 메모리 및 힙(Heap) 덤프 뜨는 방법
12684정성태6/19/202116512오류 유형: 728. Visual Studio 2022부터 DTE.get_Properties 속성 접근 시 System.MissingMethodException 예외 발생
12683정성태6/18/202117832VS.NET IDE: 166. Visual Studio 2022 - Windows Forms 프로젝트의 x86 DLL 컨트롤이 Designer에서 오류가 발생하는 문제 [1]파일 다운로드1
12682정성태6/18/202114376VS.NET IDE: 165. Visual Studio 2022를 위한 Extension 마이그레이션
12681정성태6/18/202114663오류 유형: 727. .NET 2.0 ~ 3.5 + x64 환경에서 System.EnterpriseServices 참조 시 CS8012 경고
12680정성태6/18/202116714오류 유형: 726. python2.7.exe 실행 시 0xc000007b 오류
12679정성태6/18/202116830COM 개체 관련: 23. CoInitializeSecurity의 전역 설정을 재정의하는 CoSetProxyBlanket 함수 사용법파일 다운로드1
12678정성태6/17/202115329.NET Framework: 1072. C# - CoCreateInstance 관련 Inteop 오류 정리파일 다운로드1
12677정성태6/17/202118116VC++: 144. 역공학을 통한 lxssmanager.dll의 ILxssSession 사용법 분석파일 다운로드1
12676정성태6/16/202117282VC++: 143. ionescu007/lxss github repo에 공개된 lxssmanager.dll의 CLSID_LxssUserSession/IID_ILxssSession 사용법파일 다운로드1
12675정성태6/16/202115180Java: 20. maven package 명령어 결과물로 (war가 아닌) jar 생성 방법
12674정성태6/15/202116428VC++: 142. DEFINE_GUID 사용법
12673정성태6/15/202117043Java: 19. IntelliJ - 자바(Java)로 만드는 Web App을 Tomcat에서 실행하는 방법
12672정성태6/15/202118661오류 유형: 725. IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
12671정성태6/15/202127333오류 유형: 724. Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
12670정성태6/13/202117312.NET Framework: 1071. DLL Surrogate를 이용한 Out-of-process COM 개체에서의 CoInitializeSecurity 문제파일 다운로드1
12669정성태6/11/202117505.NET Framework: 1070. 사용자 정의 GetHashCode 메서드 구현은 C# 9.0의 record 또는 리팩터링에 맡기세요.
12668정성태6/11/202120007.NET Framework: 1069. C# - DLL Surrogate를 이용한 Out-of-process COM 개체 제작파일 다운로드2
12667정성태6/10/202117806.NET Framework: 1068. COM+ 서버 응용 프로그램을 이용해 CoInitializeSecurity 제약 해결파일 다운로드1
12666정성태6/10/202115451.NET Framework: 1067. 별도 DLL에 포함된 타입을 STAThread Main 메서드에서 사용하는 경우 CoInitializeSecurity 자동 호출파일 다운로드1
12665정성태6/9/202117501.NET Framework: 1066. Wslhub.Sdk 사용으로 알아보는 CoInitializeSecurity 사용 제약파일 다운로드1
12664정성태6/9/202115307오류 유형: 723. COM+ PIA 참조 시 "This operation failed because the QueryInterface call on the COM component" 오류
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...