본문 바로가기
C#

WPF TreeView ContextMenu로 노드 삭제 및 이름 변경

by samie 2025. 4. 15.
WPF TreeView ContextMenu로 노드 삭제 및 이름 변경

🧰 WPF TreeView에 ContextMenu로 노드 삭제 및 이름 변경

이번 글에서는 TreeView 노드를 오른쪽 클릭하여 삭제하거나 이름을 변경할 수 있도록 ContextMenu를 구현해봅니다.
MVVM 패턴을 따르면서 사용자 인터페이스도 깔끔하게 유지하는 방법을 소개합니다.

1. XAML: ContextMenu 구성


<TreeView ItemsSource="{Binding Categories}">
  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
      <TextBlock Text="{Binding Name}">
        <TextBlock.ContextMenu>
          <ContextMenu>
            <MenuItem Header="이름 변경"
                      Command="{Binding DataContext.RenameCommand, RelativeSource={RelativeSource AncestorType=TreeView}}"
                      CommandParameter="{Binding}" />
            <MenuItem Header="삭제"
                      Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource AncestorType=TreeView}}"
                      CommandParameter="{Binding}" />
          </ContextMenu>
        </TextBlock.ContextMenu>
      </TextBlock>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

2. ViewModel: 명령 정의 및 바인딩


public ICommand RenameCommand { get; }
public ICommand DeleteCommand { get; }

public MainViewModel()
{
    RenameCommand = new RelayCommand<Category>(RenameCategory);
    DeleteCommand = new RelayCommand<Category>(DeleteCategory);
}

private void RenameCategory(Category category)
{
    var input = ShowInputDialog("새 이름을 입력하세요", category.Name);
    if (!string.IsNullOrWhiteSpace(input))
        category.Name = input;
}

private void DeleteCategory(Category category)
{
    if (category.Parent != null)
        category.Parent.Children.Remove(category);
    else
        Categories.Remove(category);
}

RelayCommand는 일반적인 ICommand 구현체로 사용하며, Category 모델에는 Parent 속성이 있어야 삭제 처리 시 위치를 찾기 좋습니다.

3. 이름 변경을 위한 입력 처리


public string ShowInputDialog(string title, string defaultValue)
{
    var inputDialog = new InputDialog(title, defaultValue);
    if (inputDialog.ShowDialog() == true)
        return inputDialog.ResponseText;
    return defaultValue;
}

간단한 InputDialog 윈도우를 만들어서 사용자 입력을 받을 수 있습니다. 또는 MVVM 라이브러리(예: MVVM Toolkit)의 DialogService를 활용해도 좋아요.

4. 실행 결과 및 마무리

이제 TreeView에서 노드를 오른쪽 클릭하면 "이름 변경", "삭제" 메뉴가 나타납니다.
이름을 바꾸면 즉시 반영되며, 삭제하면 트리에서 제거됩니다.

  • MVVM 패턴 유지
  • 간단한 사용자 경험 향상
  • 다양한 기능 확장 가능: 복사, 붙여넣기 등

다음 편에서는 TreeView에 검색 기능을 추가하여 대규모 트리에서도 원하는 노드를 빠르게 찾을 수 있도록 만들어보겠습니다! 🔍