繁体   English   中英

如何将命令绑定到列表框项目?

[英]How do I bind a command to a Listbox Item?

我有一个列表框。 我有绑定到列表的列表框的ItemSource。

在ItemTemplate内,我希望能够为每个项目添加一个MouseBinding。

这是我到目前为止的内容:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Border Background="Blue" CornerRadius="8" >
            <Border.InputBindings>
                <MouseBinding MouseAction="LeftClick" Command="{Binding Test}" CommandParameter="{Binding PropertyOfClickItem}" />
            </Border.InputBindings>
            <TextBlock Foreground="White" FontSize="24" FontWeight="Bold" Margin="5">
                <TextBlock.Text>
                    <MultiBinding StringFormat="{}{0}, {1} &#x0a;Seat: {2}">
                        <Binding Path="LastName" />
                        <Binding Path="FirstName" />
                        <Binding Path="Seat" />
                     </MultiBinding>
                 </TextBlock.Text>
             </TextBlock>
         </Border>

      </DataTemplate>
</ListBox.ItemTemplate>

我很困惑,因为似乎我只能绑定到ItemSource中的内容,但是我的“ Test”命令不在其中。 如何绑定到View的ViewModel中的命令,而不是绑定到列表框的ItemSource?

不仅如此,我还希望能够将所选项目的属性传递给命令。 这可能吗?

您可以使用绑定的RelativeSource属性来获取具有所需DataContext的祖先。 例如:

Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"

使用像clcto所说的相对源。

在此处查找完整答案: 列表中的WPF“静态”绑定

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM