2011-11-25 63 views
0

我想通過列表框的選定索引屬性作爲命令參數到上下文菜單項,我有命令綁定工作(感謝威爾@ElementName Binding from MenuItem in ContextMenu),但我'我的命令參數有問題。從上下文菜單項獲取父列表框選擇索引作爲CommandParamater項目

<UserControl> 
    <ListBox ItemsSource="{Binding myItems}"> 
     <ListBox.Resources> <!-- The selected item is the item the mouse is over --> 
      <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}"> 
       <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
       <Style.Triggers> 
        <DataTrigger Binding="{Binding IsMouseOver,RelativeSource={RelativeSource Self}}" 
        Value="True"> 
         <Setter Property="IsSelected" Value="True" /> 
        </DataTrigger> 
       </Style.Triggers> 
      </Style> 
     </ListBox.Resources> 

     <ListBox.ItemTemplate> 
      <DataTemplate> 
       <Button Content="Edit" Grid.Column="4" Grid.Row="0" Tag="{Binding DataContext, ElementName=ProductBacklog}"> 
        <Button.ContextMenu> 
         <ContextMenu> 
          <MenuItem Header="Remove" 
           Command="{Binding PlacementTarget.Tag.RemoveStoryClickCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" 
           CommandParameter="{Binding <!--I NEED TO BIND TO THE LISTBOX-->, Path=SelectedIndex}"/> 
         </ContextMenu> 
        </Button.ContextMenu> 
       </Button> 
      </DataTemplate> 
     </ListBox.ItemTemplate> 

    </ListBox> 
</UserControl> 

回答

1

您可以設置CommandParameter="{Binding }"到該行的當前數據項傳遞給你的命令

編輯

只注意到你的命令是在ContextMenu。 ContextMenus不是WPF默認可視化樹的一部分,因此綁定的工作方式不同。綁定到當前項,使用以下命令:

<MenuItem Header="Remove" 
      Command="{Binding PlacementTarget.Tag.RemoveStoryClickCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}" 
      CommandParameter="{Binding PlacementTarget.DataContext, 
       RelativeSource={RelativeSource FindAncestor, 
       AncestorType={x:Type ContextMenu}}}" /> 

這將綁定到的任何控制ContextMenuDataContext放置,所以在這種情況下,這將是Button.DataContext

+1

感謝您的幫助,我但在我原來的問題中出現錯誤,這是我需要的項目索引,而不是實際的項目。這可能嗎? –

+1

@EamonnMcEvoy Hrrrm可能將您的Button的DataContext設置爲指向ListBox的SelectedIndex的RelativeSource綁定? '

+0

它工作:)非常感謝! –

相關問題