c# - 如何将命令绑定(bind)到列表框项?

标签 c# wpf data-binding listbox

我有一个列表框。我将列表框的 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} &#x0a;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/

相关文章:

c# - C 中 char 点的等效 C# 类型是什么

wpf - 创建 CommandBindings 时出现 MissingMethodException

wpf - 在服务上实现 INotifyCollectionChanged 或 INotifyPropertyChanged 可以吗?

javascript - 是否有相当于 Spring :bind for binding forms and data on the front end?

c# - 从附加属性设置样式中的 WPF MenuItem 图标

c# - Max(x=>x.Time) 与 OrderByDescending(x=>x.Time).First().Time

c# - 一个web应用场景中NHibernate乐观并发的问题

c# - 如何得到多次执行伯努利实验的详细结果(概率树)

wpf - 从WPF显示和隐藏Windows 8屏幕键盘

WPF/附加属性 - 请解释为什么它有效