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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18257516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:54:08  来源:igfitidea点击:

How to pass listbox selecteditem as command parameter in a button?

wpfxamlmvvmbindinglistbox

提问by Price Jones

Here is my situation:

这是我的情况:

<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 ????}/>

What I want is to pass the Id that is currently selected in the ListBox. I have a viewmodel behind the scenes that essentially looks like this:

我想要的是传递当前在 ListBox 中选择的 Id。我在幕后有一个视图模型,它基本上是这样的:

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}
}

How can I send the currently selected item using the xaml?

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

回答by mohammad jannesary

Try this:

尝试这个:

  1. Name your listbox
  2. Update the CommandParameter to:

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

  1. 命名您的列表框
  2. 将命令参数更新为:

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