2009-10-16 4 views
20

가능한 중복 :
Specify Command for MenuItem in a DataTemplateItemsSource가있는 WPF ContextMenu - 각 항목의 명령에 바인딩하는 방법?

나는 개체 메뉴 항목을 나타냅니다 (viewmodels)의 컬렉션이 있습니다. 각각에는 MenuItem을 클릭 할 때 실행하고 싶은 명령이 있습니다. 나는의 ContextMenu를 할당해야

<ContextMenu> 
    <MenuItem Header="{Binding Text1}" Command={Binding Command1}> 
    <MenuItem Header="{Binding Text2}" Command={Binding Command2}> 
</ContextMenu> 

을하지만 사전에 항목을 모를 때 (그들은 모음에서 온) : 나는 정적으로 메뉴를하고 싶었다 경우

,이 같은 그것을 할 .ItemsSource - 텍스트를 ItemTemplate에 넣습니다.

<ContextMenu ItemsSource="{Binding MyMenuItems}"> 
    <ContextMenu.ItemTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Text2}" /> <!-- But where to put Command binding? TextBlock.Command makes no sense, and we have no access to MenuItem! --> 
     </DataTemplate> 
    </ContextMenu.ItemTemplate> 
</ContextMenu> 

이렇게하면 모든 행에 대해 MenuItem을 가져올 수 없으므로이 방법으로는 명령을 바인딩 할 수 없습니다!

어떤 조언을 해주시겠습니까? 고마워, 얘들 아! AssociatedCommand는 ICommand의 보유 뷰 모델 객체의 속성이다

+0

[http://stackoverflow.com/questions/898852/specify-command-for-menuitem-in-a-datatemplate](http://stackoverflow.com/questions/898852/specify-command- for-menuitem-in-a-datatemplate)을 사용합니다. –

답변

29
<ContextMenu.ItemContainerStyle> 
    <Style TargetType="MenuItem"> 
    <Setter Property="Command" Value="{Binding AssociatedCommand}" /> 
    </Style> 
</ContextMenu.ItemContainerStyle> 

.

+0

감사합니다. 이미 연결된 스레드에서 같은 대답을 발견했습니다 ... –

+5

두 메뉴 항목에 대한 명령을 분리하는 방법은 무엇입니까? – TrustyCoder

+0

여러 메뉴 항목에 대해 명령을 구분하는 방법은 무엇입니까? "추가"및 "제거"라고합시다. –

관련 문제