프로그래밍/WPF
[WPF] ContextMenu Binding in TreeView
흔한티벳여우
2022. 11. 28. 10:12
반응형
TreeView에 있는 데이터를 탐색기처럼 사용할 떄, 각 Item들을 오른쪽 버튼을 눌러 어떠한 작업을 할때가 있다.
이때 보통 ContextMenu를 사용하는데 Command와 CommandParameter를 사용해야하는데 일반적인 방법으론 잘 되지 않는다.
그래서 사용하는 방법이 Tag에 해당 최상위 컨트롤의 DataContext를 바인딩하고, MenuItem에서 Tag를 통해 가지고 오는 방법을 사용한다.
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}"
BasedOn="{StaticResource {x:Type TreeViewItem}}">
<Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type TreeView}}}"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="RemoveItem"
Command="{Binding PlacementTarget.Tag.RemoveItemCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
이때 CommandParameter는 오른쪽으로 선택된 아이템이 따라온다.
반응형