如何将listbox selecteditem作为命令参数传递给按钮?

Pri*_*nes 39 wpf xaml binding listbox mvvm

这是我的情况:

<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 ????}/>
Run Code Online (Sandbox Code Playgroud)

我想要的是传递ListBox中当前选中的Id.我有幕后的viewmodel,基本上是这样的:

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}
}
Run Code Online (Sandbox Code Playgroud)

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

moh*_*ary 65

试试这个:

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

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