【问题标题】:Getting parent ListBox selected index as CommandParamater from context menu item从上下文菜单项获取父 ListBox 选定索引作为 CommandParamater
【发布时间】:2011-11-25 15:21:39
【问题描述】:

我正在尝试将列表框的 Selected Index 属性作为命令参数传递给上下文菜单项,我的命令绑定正常工作(感谢 Will @ ElementName Binding from MenuItem in ContextMenu),但我的命令参数有问题。

<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>

【问题讨论】:

    标签: wpf data-binding listbox contextmenu itemtemplate


    【解决方案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}}}" />
    

    这将绑定到ContextMenu所在的任何控件的DataContext,所以在这种情况下它将是Button.DataContext

    【讨论】:

    • 感谢您的帮助,但我在原始问题中犯了一个错误,这是我需要的项目索引,而不是实际项目。这可能吗?
    • @EamonnMcEvoy Hrrrm 也许将您的 Button 的 DataContext 设置为指向 ListBox 的 SelectedIndex 的 RelativeSource 绑定? &lt;Button DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}}, Path=SelectedIndex}" ... /&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多