Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

데이터 바인딩된 트리에서 부모 노드 찾는 방법


이전 WinForm 시절에는 보통 TreeView를 사용할 때 해당 TreeViewItem을 직접 조작했기 때문에 부모 노드를 찾는 방법이 간단했습니다.

그런데, WPF로 오면서 데이터 바인딩을 하는 방식에서는 TreeViewItem의 직접적인 노출이 지양되어 SelectedItem을 구해도 바인딩된 타입만 나올 뿐 TreeViewItem을 구할 수 없습니다.

물론, 좀 까다롭긴 하지만 구하는 방법이 있습니다.

Getting TreeViewItem's From Data Bound Items
; http://www.michaelbraude.com/2008/02/getting-treeviewitem-from-data-bound.html

WPF는 트리의 각 노드별로 ItemContainerGenerator를 가지고 있고 그 generator를 이용하면 해당 노드의 자식 TreeViewItem을 구할 수 있습니다. 일례로, 다음과 같은 트리 구조가 있을 때,

Root0
   Child0
   Child1
   Child2

Root1

만약, Child1에 해당하는 TreeViewItem을 구하고 싶다면 다음과 같은 식으로 TreeViewItem을 구해올 수 있습니다.

TreeViewItem root0Item = this.treeView.ItemContainerGenerator.ContainerFromIndex(0) 
                           as TreeViewItem;

TreeViewItem child1Item = root0Item.ItemContainerGenerator.ContainerFromIndex(1)
                           as TreeViewItem;
        // 또는 ContainerFromItem를 사용하면 데이터 인스턴스로부터 TreeViewItem을 구함.

따라서, 데이터 바인딩된 인스턴스의 TreeViewItem을 구하고 싶다면, 최상단 트리로부터 재귀적으로 탐색을 하면서 찾아가야 합니다. 여간 귀찮은 작업이 아닐 수 없지요.




이제, 해당 인스턴스의 TreeViewItem을 구했다고 가정하고.
그렇다면 그 노드의 상위 노드를 구해야 한다면 또 어떻게 해야 할까요? 다시 재귀적으로 탐색을 하던가, 아니면 이전에 탐색을 했을 때 부모 노드까지 같이 저장해 두면 해결이 됩니다.

간혹, 아래와 VisualTreeHelper로 TreeViewItem의 부모 노드를 찾으려고 하는 분들이 있는데요. 그런 분들은 아래의 글에 달린 댓글을 보시기 바랍니다.

Get a TreeViewItem’s Parent item
; http://quickduck.com/blog/2009/09/15/get-a-treeviewitems-parent-item/

즉, 운영체제별로, 그리고 그 운영체제에서 사용되는 테마에 따라서, 혹은 WPF Designer가 재작성한 스타일에 따라서 Visual Tree는 얼마든지 바뀔 수 있기 때문에 단순히 TreeViewItem의 "한 단계"만 VisualTreeHelper.GetParent 하시면 안됩니다. 역시 그것도 상위로 계속 루프를 돌면서 인스턴스가 TreeViewItem이 나올 때까지 계속해야 합니다.




어쩄든, 결론은... ^^; 너무 복잡합니다. 그냥 데이터 바인딩만 시키면 알아서 자동으로 되면 좋지 않을까요?
이에 대한 해답은 예전의 글에서 이미 소개해 드린 것이나 다름없습니다.

WPF - TreeView 자동 스크롤 기능 해지
; https://www.sysnet.pe.kr/2/0/781

즉, 트리 스스로 TreeViewItem이 생성될 때마다 자신의 부모 노드를 기록해 놓는 것입니다.

public class ParentChildTreeView : TreeView
{
    public class ParentChildTreeViewItem : TreeViewItem
    {
        public ParentChildTreeViewItem()
            : base()
        {
        }

        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);

            ITreeViewParentLink support = item as ITreeViewParentLink;
            if (support == null)
            {
                return;
            }

            support.ParentItem = ItemsControl.ItemsControlFromItemContainer(element) as TreeViewItem;
        }

        protected override DependencyObject GetContainerForItemOverride()
        {
            return new ParentChildTreeViewItem();
        }
    }

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new ParentChildTreeViewItem();
    }
}

이렇게 재정의된 ParentChildTreeView를 사용하게 되면, 다음과 같이 간단하게 부모 노드를 구해올 수 있습니다.

private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    MyClassT myClass = e.NewValue as MyClassT;
    if (myClass.ParentData == null)
    {
        // 부모 노드가 없는 최상위 노드
        return;
    }

    // 부모 노드의 Name 속성을 출력
    Debug.WriteLine(myClass.ParentData.Name);
}

이를 활용하면, 일반적인 .NET Entity 클래스의 계층 구조를 표현할 때 WPF TreeView를 붙여줌으로써 자동적으로 부모/자식 관계를 해결하는 것도 가능합니다. ^^

첨부 파일은 위의 코드를 테스트 해 볼 수 있는 간단한 프로젝트입니다.



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







[최초 등록일: ]
[최종 수정일: 4/11/2022]

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

비밀번호

댓글 작성자
 



2018-03-29 08시11분
[최병철] 아, WPF 의 트리뷰가 진입장벽이 이렇게 높을 줄은 몰랐습니다.

TreeViewItem root0Item = this.treeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
// 이 코드가 아주 도움이 되었습니다.

아이템을 코드로 선택하는 것 조차도 어떨 때는 되고, 어떨 때는 null 을 반환했던 것이 바로 말씀하신 아래의 내용때문이었군요.

"WPF는 트리의 각 노드별로 ItemContainerGenerator 를 가지고 있고 그 generator를 이용하면 해당 노드의 자식 TreeViewItem을 구할 수 있습니다"


CotainerFromIndex 말고,
ContainerFromItem 함수를 호출할 때, rootitem 이외에는 왜 null 을 반환하는지 알게되었습니다.
정말 감사합니다. 아~ 후련해!
[guest]

... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923337오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921819.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920628개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921166개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201917088오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916915오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916610오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918320개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926197개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919132오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919312오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924577개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201919030오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920648오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918969오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919729오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922798오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922059Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920150VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916516오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919967Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918180오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201917061오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918344.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915672오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920905오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...