我有一个列表框。我将列表框的 ItemSource 绑定(bind)到列表。
在 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} 
Seat: {2}">
<Binding Path="LastName" />
<Binding Path="FirstName" />
<Binding Path="Seat" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
我很困惑,因为我似乎只能绑定(bind)到 ItemSource 中的东西,但我的“Test”命令不在其中。如何绑定(bind)到 View 的 ViewModel 中的命令,而不是绑定(bind)到列表框的 ItemSource?
不仅如此,我还希望能够将所选项目的属性传递给命令。这可能吗?
最佳答案
您可以使用RelativeSource
绑定(bind)的属性以获取具有所需 DataContext 的祖先。例如:
Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
关于c# - 如何将命令绑定(bind)到列表框项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32958775/