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]

... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12416정성태11/19/202017416오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017539.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019745VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018674.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020767.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202017539오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202017751디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019581.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034832도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019957.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020896.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018885.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019499.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018303.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019865.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202019156VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015324오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018776.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018435오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018484.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015427VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202018266오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015894오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015433오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019968.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019741디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...