如何将命令绑定到列表框项?
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} 
Seat: {2}">
<Binding Path="LastName" />
<Binding Path="FirstName" />
<Binding Path="Seat" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
我很困惑,因为我似乎只能绑定到 ItemSource 中的东西,但我的 "Test" 命令不在其中。如何绑定到视图的 ViewModel 中的命令,而不是绑定到列表框的 ItemSource?
不仅如此,我还希望能够将所选项目的 属性 传递给命令。这可能吗?
您可以使用绑定的 RelativeSource
属性 来获取具有所需 DataContext 的祖先。例如:
Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
使用 clcto 所说的相对来源。
在此处查看完整答案:
我有一个列表框。我将列表框的 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} 
Seat: {2}">
<Binding Path="LastName" />
<Binding Path="FirstName" />
<Binding Path="Seat" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
我很困惑,因为我似乎只能绑定到 ItemSource 中的东西,但我的 "Test" 命令不在其中。如何绑定到视图的 ViewModel 中的命令,而不是绑定到列表框的 ItemSource?
不仅如此,我还希望能够将所选项目的 属性 传递给命令。这可能吗?
您可以使用绑定的 RelativeSource
属性 来获取具有所需 DataContext 的祖先。例如:
Command="{Binding DataContext.Test, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}"
使用 clcto 所说的相对来源。
在此处查看完整答案: