wpf - 如何将列表框选定项作为按钮中的命令参数传递?

标签 wpf xaml mvvm binding listbox

这是我的情况:

<ListBox ItemsSource="{Binding Path=AvailableUsers}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=Id}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
<Button Command="{Binding Path=Load}" CommandParameter={???? What goes here ????}/>

我想要的是传递当前在列表框中选择的 Id。我在幕后有一个 View 模型,基本上如下所示:

public class ViewModel : DependencyObject
{
    ICommand Load { get; set; }

    // dependency property but I didn't bother to write it out like one
    List<User> AvailableUsers { get; set}
}

如何使用 xaml 发送当前选定的项目?

最佳答案

试试这个:

  1. 为您的列表框命名
  2. 将 CommandParameter 更新为:

    CommandParameter="{Binding ElementName=listBox1,Path=SelectedItem}"

关于wpf - 如何将列表框选定项作为按钮中的命令参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18257516/

相关文章:

c# - WPF UI 自动化问题

xaml - 在 XAML 命名空间中找不到类型

c# - 将文本 block 绑定(bind)到两个属性

c# - 与从 XAML 创建的 View 模型相关的问题

c# - 如何检查3个手指是否放在屏幕上

c# - 在 DataTemplate 中绑定(bind)图像源时出错

wpf - 在多个 WPF 控件之间共享列宽

android - 从 ViewHolder 或 ViewHolder 的 ViewModel 访问 RecyclerView.Adapter 的方法

wpf - WPF MVVM 应用程序的最佳设计模式

c# - 使用 CollectionViewSource 在数据网格上进行分组的问题